ygnmi

package
v0.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 8, 2024 License: Apache-2.0 Imports: 23 Imported by: 85

Documentation

Overview

Package ygnmi contains gNMI client library for use with a ygot Schema.

Index

Examples

Constants

View Source
const (
	// PathStructInterfaceName is the name for the interface implemented by all
	// generated path structs.
	PathStructInterfaceName = "PathStruct"
	// PathBaseTypeName is the type name of the common embedded struct
	// containing the path information for a path struct.
	PathBaseTypeName = "NodePath"
	// FakeRootBaseTypeName is the type name of the fake root struct which
	// should be embedded within the fake root path struct.
	FakeRootBaseTypeName = "DeviceRootBase"
)
View Source
const (
	// OriginOverride is the key to custom opt that sets the path origin.
	OriginOverride = "origin-override"
)

Variables

View Source
var (
	// ErrNotPresent is returned by Get when there are no a values at a path.
	ErrNotPresent = fmt.Errorf("value not present")
	// Continue should returned by predicates to indicate the condition is not reached.
	Continue = fmt.Errorf("condition not true")
)

Functions

func BatchDelete

func BatchDelete[T any](sb *SetBatch, q ConfigQuery[T])

BatchDelete stores a delete operation in the SetBatch.

func BatchReplace

func BatchReplace[T any](sb *SetBatch, q ConfigQuery[T], val T)

BatchReplace stores a replace operation in the SetBatch.

func BatchUnionReplace added in v0.8.6

func BatchUnionReplace[T any](sb *SetBatch, q ConfigQuery[T], val T)

BatchUnionReplace stores a union_replace operation in the SetBatch.

https://github.com/openconfig/reference/blob/master/rpc/gnmi/gnmi-union_replace.md

func BatchUnionReplaceCLI added in v0.8.6

func BatchUnionReplaceCLI(sb *SetBatch, nos, ascii string)

BatchUnionReplaceCLI stores a CLI union_replace operation in the SetBatch.

https://github.com/openconfig/reference/blob/master/rpc/gnmi/gnmi-union_replace.md

func BatchUpdate

func BatchUpdate[T any](sb *SetBatch, q ConfigQuery[T], val T)

BatchUpdate stores an update operation in the SetBatch.

func Get

func Get[T any](ctx context.Context, c *Client, q SingletonQuery[T], opts ...Option) (T, error)

Get fetches the value of a SingletonQuery with a ONCE subscription, returning an error that wraps ErrNotPresent if the value is not present. Use Lookup to get metadata and tolerate non-present data.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Get a value at path.
	// No metadata is returned, and an error is returned if not present.
	path := exampleocpath.Root().Parent().Child()
	child, err := ygnmi.Get(context.Background(), c, path.State())
	if err != nil {
		log.Fatalf("Failed to Get: %v", err)
	}

	fmt.Printf("Child: %v\n", child)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

Example (Batch)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Create a new batch object and add paths to it.
	b := new(exampleocpath.Batch)
	// Note: the AddPaths accepts paths not queries.
	b.AddPaths(exampleocpath.Root().RemoteContainer().ALeaf(), exampleocpath.Root().Model().SingleKeyAny().Value())
	// Get the values of the paths in the paths, a Batch Query always returns the root object.
	val, err := ygnmi.Get(context.Background(), c, b.State())
	if err != nil {
		log.Fatalf("Get failed: %v", err)
	}
	fmt.Printf("Got aLeaf %v, SingleKey[foo]: %v", val.GetRemoteContainer().GetALeaf(), val.GetModel().GetSingleKey("foo").GetValue())

}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func GetAll

func GetAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], opts ...Option) ([]T, error)

GetAll fetches the value of a WildcardQuery with a ONCE subscription skipping any non-present paths. It returns an error that wraps ErrNotPresent if no values were received. Use LookupAll to also get metadata containing the returned paths.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Get on the keys of the SingleKey list
	path := exampleocpath.Root().Model().SingleKeyAny().Value()
	vals, err := ygnmi.GetAll(context.Background(), c, path.State())
	if err != nil {
		log.Fatalf("Failed to Lookup: %v", err)
	}

	// Get the value of each list element.
	// With GetAll it is impossible to know the path associated with a value,
	// so use LookupAll or Batch with with wildcard path instead.
	for _, val := range vals {
		fmt.Printf("Got List Val %v", val)
	}
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func LatestRecvTimestamp

func LatestRecvTimestamp(data []*DataPoint) time.Time

LatestRecvTimestamp returns the latest recv timestamp of the input datapoints. If datapoints is empty, then the zero time is returned.

func LatestTimestamp

func LatestTimestamp(data []*DataPoint) time.Time

LatestTimestamp returns the latest timestamp of the input datapoints. If datapoints is empty, then the zero time is returned.

func ModifyKey

func ModifyKey(n *NodePath, name string, value interface{})

ModifyKey updates a NodePath's key value.

func NewContext added in v0.10.2

func NewContext(ctx context.Context, q UntypedQuery) context.Context

NewContext returns a new Context carrying ygnmi request-scoped values.

func ResolvePath

func ResolvePath(n PathStruct) (*gpb.Path, map[string]interface{}, error)

ResolvePath is a helper which returns the resolved *gpb.Path of a PathStruct node as well as the root node's customData.

func ResolveRelPath

func ResolveRelPath(n PathStruct) ([]*gpb.PathElem, []error)

ResolveRelPath returns the partial []*gpb.PathElem representing the PathStruct's relative path.

Types

type AnyQuery

type AnyQuery[T any] interface {
	UntypedQuery
	// contains filtered or unexported methods
}

AnyQuery is a generic gNMI query for wildcard or non-wildcard state or config paths.

type Batch added in v0.2.3

type Batch[T any] struct {
	// contains filtered or unexported fields
}

Batch contains a collection of paths. Calling State() or Config() on the batch returns a query that can be used to Lookup, Watch, etc on multiple paths at once.

func NewBatch added in v0.2.3

func NewBatch[T any](root SingletonQuery[T]) *Batch[T]

NewBatch creates a batch object. All paths in the batch must be children of the root query.

func (*Batch[T]) AddPaths added in v0.2.3

func (b *Batch[T]) AddPaths(paths ...UntypedQuery) error

AddPaths adds the paths to the batch. Paths must be children of the root.

func (*Batch[T]) Query added in v0.2.3

func (b *Batch[T]) Query() SingletonQuery[T]

Query returns a Query that can be used in gNMI operations. The returned query is immutable, adding paths does not modify existing queries.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is used to perform gNMI requests.

func NewClient

func NewClient(c gpb.GNMIClient, opts ...ClientOption) (*Client, error)

NewClient creates a new client with specified options.

func (*Client) String added in v0.7.9

func (c *Client) String() string

String returns a string representation of Client. This output is unstable.

type ClientOption

type ClientOption func(d *Client) error

ClientOption configures a client with custom options.

func WithRequestLogLevel added in v0.6.1

func WithRequestLogLevel(l log.Level) ClientOption

WithRequestLogLevel overrides the default info logging level (1) for gNMI request dumps. i.e. SetRequest, SubscribeRequest, GetRequest.

func WithTarget

func WithTarget(t string) ClientOption

WithTarget sets the target of the gpb.Path for all requests made with this client.

type Collector

type Collector[T any] struct {
	// contains filtered or unexported fields
}

Collector represents an ongoing collection of telemetry values.

func Collect

func Collect[T any](ctx context.Context, c *Client, q SingletonQuery[T], opts ...Option) *Collector[T]

Collect starts an asynchronous collection of the values at the query with a STREAM subscription. Calling Await on the return Collection waits until the context is cancelled and returns the collected values.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	path := exampleocpath.Root().Parent().Child()

	// Use a context with a timeout, so that Collect doesn't continue indefinitely.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// Collect values at path until context deadline is reached.
	collector := ygnmi.Collect(ctx, c, path.State())
	vals, err := collector.Await()
	if err != nil {
		log.Fatalf("Failed to Collect: %v", err)
	}

	fmt.Printf("Got %d values", len(vals))
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func CollectAll

func CollectAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], opts ...Option) *Collector[T]

CollectAll starts an asynchronous collection of the values at the query with a STREAM subscription. Calling Await on the return Collection waits until the context is cancelled to elapse and returns the collected values.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	path := exampleocpath.Root().Model().SingleKeyAny().Value()

	// Use a context with a timeout, so that Collect doesn't continue indefinitely.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// Collect values at path until context deadline is reached.
	collector := ygnmi.CollectAll(ctx, c, path.State())
	vals, err := collector.Await()
	if err != nil {
		log.Fatalf("Failed to Collect: %v", err)
	}

	fmt.Printf("Got %d values", len(vals))
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func (*Collector[T]) Await

func (c *Collector[T]) Await() ([]*Value[T], error)

Await waits for the collection to finish and returns all received values. When Await returns the watcher is closed, and Await may not be called again. Note: the func blocks until the context is cancelled.

type ComplianceErrors

type ComplianceErrors struct {
	// PathErrors are compliance errors encountered due to an invalid schema path.
	PathErrors []*TelemetryError
	// TypeErrors are compliance errors encountered due to an invalid type.
	TypeErrors []*TelemetryError
	// ValidateErrors are compliance errors encountered while doing schema
	// validation on the unmarshalled data.
	ValidateErrors []error
}

ComplianceErrors contains the compliance errors encountered from an Unmarshal operation.

func (*ComplianceErrors) String

func (c *ComplianceErrors) String() string

type CompressionInfo added in v0.8.0

type CompressionInfo struct {
	// PreRelPath is the list of qualified path elements prior to the
	// compressed-out node.
	PreRelPath []string
	// PostRelPath is the list of qualified path elements after the
	// compressed-out node.
	PostRelPath []string
}

CompressionInfo contains information about a compressed path element for a node which points to a path element that's compressed out.

e.g. for OpenConfig's /interfaces/interface, if a path points to /interfaces, then CompressionInfo will be populated with the following: - PreRelPath: []{"openconfig-interfaces:interfaces"} - PostRelPath: []{"openconfig-interfaces:interface"}

type ConfigQuery

type ConfigQuery[T any] interface {
	AnyQuery[T]
	// IsConfig() allows this interface to be use in config funcs.
	IsConfig()
	// IsSingleton restricts this interface to be used only where a singleton path is expected.
	IsSingleton()
}

ConfigQuery is a non-wildcard config gNMI query.

type ConfigQueryStruct added in v0.8.0

type ConfigQueryStruct[T any] struct {
	// contains filtered or unexported fields
}

ConfigQueryStruct is implementation of ConfigQuery interface for leaf nodes. Note: Do not use this type directly, instead use the generated Path API.

func NewConfigQuery added in v0.8.0

func NewConfigQuery[T any](goStructName string, state, shadowpath, leaf, scalar, compressedSchema, listContainer bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema, subPaths []PathStruct, compressInfo *CompressionInfo) *ConfigQueryStruct[T]

NewConfigQuery creates a new NewLeafConfigQuery object.

func (*ConfigQueryStruct[T]) IsConfig added in v0.8.0

func (q *ConfigQueryStruct[T]) IsConfig()

IsConfig restricts this struct to be used only where a config path is expected.

func (*ConfigQueryStruct[T]) IsSingleton added in v0.8.0

func (q *ConfigQueryStruct[T]) IsSingleton()

IsSingleton restricts this struct to be used only where a singleton path is expected.

func (*ConfigQueryStruct) IsState added in v0.8.0

func (q *ConfigQueryStruct) IsState() bool

IsState returns if the Query is for a state or config path.

func (*ConfigQueryStruct) PathStruct added in v0.8.0

func (q *ConfigQueryStruct) PathStruct() PathStruct

PathStruct returns the path struct containing the path for the Query.

func (*ConfigQueryStruct) String added in v0.8.0

func (q *ConfigQueryStruct) String() string

String returns gNMI path as string for the query.

type DataPoint

type DataPoint struct {
	// Path of the received value.
	Path *gpb.Path
	// Value of the data; nil means delete.
	Value *gpb.TypedValue
	// Timestamp is the time at which the value was updated on the device.
	Timestamp time.Time
	// RecvTimestamp is the time the update was received.
	RecvTimestamp time.Time
	// Sync indicates whether the received datapoint was gNMI sync response.
	Sync bool
}

DataPoint is a value of a gNMI path at a particular time.

func (*DataPoint) String added in v0.8.9

func (d *DataPoint) String() string

type DeviceRootBase

type DeviceRootBase struct {
	*NodePath
	// contains filtered or unexported fields
}

DeviceRootBase represents the fakeroot for all YANG schema elements.

func NewDeviceRootBase

func NewDeviceRootBase() *DeviceRootBase

NewDeviceRootBase creates a DeviceRootBase.

func (*DeviceRootBase) CustomData

func (d *DeviceRootBase) CustomData() map[string]interface{}

CustomData returns the customData field of the DeviceRootBase struct.

func (*DeviceRootBase) PutCustomData

func (d *DeviceRootBase) PutCustomData(key string, val interface{})

PutCustomData modifies an entry in the customData field of the DeviceRootBase struct.

type ExtractFn

type ExtractFn[T any] func(ygot.ValidatedGoStruct) (T, bool)

ExtractFn is the type for the func that extracts a concrete val from a GoStruct.

type NodePath

type NodePath struct {
	// contains filtered or unexported fields
}

NodePath is a common embedded type within all path structs. It keeps track of the necessary information to create the relative schema path as a []*gpb.PathElem during later processing using the Resolve() method, thereby delaying any errors being reported until that time.

func NewNodePath

func NewNodePath(relSchemaPath []string, keys map[string]interface{}, p PathStruct) *NodePath

NewNodePath is the constructor for NodePath.

type Option added in v0.2.0

type Option func(*opt)

Option can be used modify the behavior of the gNMI requests used by the ygnmi calls (Lookup, Await, etc.).

func WithEncoding added in v0.6.0

func WithEncoding(enc gpb.Encoding) Option

WithEncoding creates an option to set the Encoding for all Subscribe or Get requests. The default encoding is PROTO. This does not apply when using WithUseGet, whith uses JSON_IETF encoding.

func WithSampleInterval added in v0.8.10

func WithSampleInterval(d time.Duration) Option

WithSampleInterval creates an option to set the sample interval in the Subcribe request. NOTE: The subscription mode must be set to SAMPLE for this to have an effect. This option is only relevant for Watch, WatchAll, Collect, CollectAll, Await which are STREAM subscriptions. The mode applies to all paths in the Subcription.

func WithSetFallbackEncoding added in v0.6.1

func WithSetFallbackEncoding() Option

WithSetFallbackEncoding creates an option that fallback to encoding SetRequests with JSON or an Any proto. Fallback encoding is if the parameter is neither GoStruct nor a leaf for non OpenConfig paths. This option is only relevant for Update and Replace.

func WithSetPreferProtoEncoding added in v0.6.1

func WithSetPreferProtoEncoding() Option

WithSetPreferProtoEncoding creates an option that prefers encoding SetRequest using proto encoding. This option is only relevant for Update and Replace.

func WithSubscriptionMode added in v0.2.0

func WithSubscriptionMode(mode gpb.SubscriptionMode) Option

WithSubscriptionMode creates an option to use input instead of the default (TARGET_DEFINED). This option is only relevant for Watch, WatchAll, Collect, CollectAll, Await which are STREAM subscriptions. The mode applies to all paths in the Subcription.

func WithUseGet added in v0.2.0

func WithUseGet() Option

WithUseGet creates an option to use gnmi.Get instead of gnmi.Subscribe. This can only be used on Get, GetAll, Lookup, and LookupAll.

type PathStruct

type PathStruct interface {
	// contains filtered or unexported methods
}

PathStruct is an interface that is implemented by any generated path struct type; it allows for generic handling of a path struct at any node.

type RequestValues added in v0.10.2

type RequestValues struct {
	// StateFiltered is a key type that means that the query is
	// uninterested in /state paths and will filter them out.
	StateFiltered bool
	// ConfigFiltered is a key type that means that the query is
	// uninterested in /config paths and will filter them out.
	ConfigFiltered bool
}

RequestValues contains request-scoped values for ygnmi queries.

func FromContext added in v0.10.2

func FromContext(ctx context.Context) *RequestValues

FromContext extracts certain ygnmi request-scoped values, if present.

type Result

type Result struct {
	// RawResponse is the raw gNMI response received from the server.
	RawResponse *gpb.SetResponse
	// Timestamp is the timestamp from the SetResponse as a native Go time struct.
	Timestamp time.Time
}

Result is the result of a Set request.

func Delete

func Delete[T any](ctx context.Context, c *Client, q ConfigQuery[T], opts ...Option) (*Result, error)

Delete deletes the configuration at the given query path.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Perform the Update request.
	res, err := ygnmi.Delete(context.Background(), c, exampleocpath.Root().Parent().Child().One().Config())
	if err != nil {
		log.Fatalf("Delete failed: %v", err)
	}
	fmt.Printf("Timestamp: %v", res.Timestamp)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func Replace

func Replace[T any](ctx context.Context, c *Client, q ConfigQuery[T], val T, opts ...Option) (*Result, error)

Replace replaces the configuration at the given query path with the val.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
	"github.com/openconfig/ygot/ygot"
)

func main() {
	c := initClient()
	// Perform the Replace request.
	res, err := ygnmi.Replace(context.Background(), c, exampleocpath.Root().RemoteContainer().Config(), &exampleoc.RemoteContainer{ALeaf: ygot.String("foo")})
	if err != nil {
		log.Fatalf("Update failed: %v", err)
	}
	fmt.Printf("Timestamp: %v", res.Timestamp)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func Update

func Update[T any](ctx context.Context, c *Client, q ConfigQuery[T], val T, opts ...Option) (*Result, error)

Update updates the configuration at the given query path with the val.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Perform the Update request.
	res, err := ygnmi.Update(context.Background(), c, exampleocpath.Root().Parent().Child().Three().Config(), exampleoc.Child_Three_TWO)
	if err != nil {
		log.Fatalf("Update failed: %v", err)
	}
	fmt.Printf("Timestamp: %v", res.Timestamp)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

type SetBatch

type SetBatch struct {
	// contains filtered or unexported fields
}

SetBatch allows multiple Set operations (Replace, Update, Delete) to be applied as part of a single Set transaction. Use BatchUpdate, BatchReplace, BatchDelete to add operations, and then call the Set method to send the SetRequest.

func (*SetBatch) Set

func (sb *SetBatch) Set(ctx context.Context, c *Client, opts ...Option) (*Result, error)

Set performs the gnmi.Set request with all queued operations.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
	"github.com/openconfig/ygot/ygot"
)

func main() {
	c := initClient()
	b := new(ygnmi.SetBatch)

	// Add set operations to a batch request.
	ygnmi.BatchUpdate(b, exampleocpath.Root().Parent().Child().Three().Config(), exampleoc.Child_Three_TWO)
	ygnmi.BatchDelete(b, exampleocpath.Root().Parent().Child().One().Config())
	ygnmi.BatchReplace(b, exampleocpath.Root().RemoteContainer().Config(), &exampleoc.RemoteContainer{ALeaf: ygot.String("foo")})

	// Perform the gnmi Set request.
	res, err := b.Set(context.Background(), c)
	if err != nil {
		log.Fatalf("Set failed: %v", err)
	}
	fmt.Printf("Timestamp: %v", res.Timestamp)

	exampleocpath.Root().Model().SingleKeyAny().Config()
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

type SingletonQuery

type SingletonQuery[T any] interface {
	AnyQuery[T]
	// IsSingleton restricts this interface to be used only where a singleton path is expected.
	IsSingleton()
}

SingletonQuery is a non-wildcard gNMI query.

type SingletonQueryStruct added in v0.8.0

type SingletonQueryStruct[T any] struct {
	// contains filtered or unexported fields
}

SingletonQueryStruct is implementation of SingletonQuery interface. Note: Do not use this type directly, instead use the generated Path API.

func NewSingletonQuery added in v0.8.0

func NewSingletonQuery[T any](goStructName string, state, shadowpath, leaf, scalar, compressedSchema, listContainer bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema, subPaths []PathStruct, compressInfo *CompressionInfo) *SingletonQueryStruct[T]

NewSingletonQuery creates a new SingletonQueryStruct object.

func (*SingletonQueryStruct[T]) IsSingleton added in v0.8.0

func (q *SingletonQueryStruct[T]) IsSingleton()

IsSingleton prevents this struct from being used where a wildcard path is expected.

func (*SingletonQueryStruct) IsState added in v0.8.0

func (q *SingletonQueryStruct) IsState() bool

IsState returns if the Query is for a state or config path.

func (*SingletonQueryStruct) PathStruct added in v0.8.0

func (q *SingletonQueryStruct) PathStruct() PathStruct

PathStruct returns the path struct containing the path for the Query.

func (*SingletonQueryStruct) String added in v0.8.0

func (q *SingletonQueryStruct) String() string

String returns gNMI path as string for the query.

type TelemetryError

type TelemetryError struct {
	Path  *gpb.Path
	Value *gpb.TypedValue
	Err   error
}

TelemetryError stores the path, value, and error string from unsuccessfully unmarshalling a datapoint into a YANG schema.

func (*TelemetryError) String

func (t *TelemetryError) String() string

type UntypedQuery added in v0.9.0

type UntypedQuery interface {
	// PathStruct returns to path struct used for unmarshalling and schema validation.
	// This path must correspond to T (the parameterized type of the interface).
	PathStruct() PathStruct

	// IsState returns if the path for this query is a state node.
	IsState() bool
	// contains filtered or unexported methods
}

UntypedQuery is a generic gNMI query for wildcard or non-wildcard state or config paths. Supported operations: Batch.

Since it is untyped, it is only suitable for representing the metadata of the query instead of initiating gNMI operations.

type Value

type Value[T any] struct {

	// Path is the sample's YANG path.
	Path *gpb.Path
	// Timestamp is the sample time.
	Timestamp time.Time
	// RecvTimestamp is the time the test received the sample.
	RecvTimestamp time.Time
	// ComplianceErrors contains the compliance errors encountered from an Unmarshal operation.
	ComplianceErrors *ComplianceErrors
	// contains filtered or unexported fields
}

Value contains a value received from a gNMI request and its metadata.

func Await

func Await[T any](ctx context.Context, c *Client, q SingletonQuery[T], val T, opts ...Option) (*Value[T], error)

Await observes values at Query with a STREAM subscription, blocking until a value that is deep equal to the specified val is received or the context is cancelled. To wait for a generic predicate, or to make a non-blocking call, use the Watch method instead.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
	"github.com/openconfig/ygot/ygot"
)

func main() {
	c := initClient()
	path := exampleocpath.Root().Parent().Child()

	// Use a context with a timeout, so that Await doesn't continue indefinitely.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	want := &exampleoc.Parent_Child{
		Two: ygot.String("good"),
	}

	// Wait until the values at the path is equal to want.
	child, err := ygnmi.Await(ctx, c, path.State(), want)
	if err != nil {
		log.Fatalf("Failed to Await: %v", err)
	}
	// Check if the value is present.
	val, ok := child.Val()
	if !ok {
		log.Fatal("No value at path")
	}
	fmt.Printf("Last Value: %v\n", val)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func Lookup

func Lookup[T any](ctx context.Context, c *Client, q SingletonQuery[T], opts ...Option) (*Value[T], error)

Lookup fetches the value of a SingletonQuery with a ONCE subscription.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Lookup a value at path.
	path := exampleocpath.Root().Parent().Child()
	val, err := ygnmi.Lookup(context.Background(), c, path.State())
	if err != nil {
		log.Fatalf("Failed to Lookup: %v", err)
	}

	// Check if the value is present.
	child, ok := val.Val()
	if !ok {
		log.Fatal("No value at path")
	}
	fmt.Printf("Child: %v\n, RecvTimestamo %v", child, val.RecvTimestamp)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func LookupAll

func LookupAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], opts ...Option) ([]*Value[T], error)

LookupAll fetches the values of a WildcardQuery with a ONCE subscription. It returns an empty list if no values are present at the path.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// LookupAll on the keys of the SingleKey list
	path := exampleocpath.Root().Model().SingleKeyAny().Value()
	vals, err := ygnmi.LookupAll(context.Background(), c, path.State())
	if err != nil {
		log.Fatalf("Failed to Lookup: %v", err)
	}

	// Get the value of each list element.
	for _, val := range vals {
		if listVal, ok := val.Val(); ok {
			fmt.Printf("Got List Val %v at path %v", listVal, val.Path)
		}
	}
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func (*Value[T]) IsPresent

func (v *Value[T]) IsPresent() bool

IsPresent returns whether the value is present.

func (*Value[T]) SetVal

func (v *Value[T]) SetVal(val T) *Value[T]

SetVal sets the value and marks it present and returns the receiver.

func (*Value[T]) String added in v0.5.0

func (v *Value[T]) String() string

String returns a user-readable string for the value.

func (*Value[T]) Val

func (v *Value[T]) Val() (T, bool)

Val returns the val and whether it is present.

type Watcher

type Watcher[T any] struct {
	// contains filtered or unexported fields
}

Watcher represents an ongoing watch of telemetry values.

func Watch

func Watch[T any](ctx context.Context, c *Client, q SingletonQuery[T], pred func(*Value[T]) error, opts ...Option) *Watcher[T]

Watch starts an asynchronous STREAM subscription, evaluating each observed value with the specified predicate. The predicate must return ygnmi.Continue to continue the Watch. To stop the Watch, return nil for a success or a non-nil error on failure. Watch can also be stopped by setting a deadline on or canceling the context. Calling Await on the returned Watcher waits for the subscription to complete. It returns the last observed value and a boolean that indicates whether that value satisfies the predicate.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Watch a path
	path := exampleocpath.Root().Parent().Child()
	// Use a context with a timeout, so that Watch doesn't continue indefinitely.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	watcher := ygnmi.Watch(ctx, c, path.State(), func(v *ygnmi.Value[*exampleoc.Parent_Child]) error {
		if c, ok := v.Val(); ok {
			if c.GetOne() == "good" {
				// Return nil to indicate success and stop evaluating predicate.
				return nil
			} else if c.GetTwo() == "bad" {
				// Return a non-nil to indicate failure and stop evaluation predicate.
				// This error is returned by Await().
				return fmt.Errorf("unexpected value")
			}
		}

		// Return ygnmi.Continue to continue evaluating the func.
		return ygnmi.Continue
	})
	// Child is the last value received.
	child, err := watcher.Await()
	if err != nil {
		log.Fatalf("Failed to Watch: %v", err)
	}
	// Check if the value is present.
	val, ok := child.Val()
	if !ok {
		log.Fatal("No value at path")
	}
	fmt.Printf("Last Value: %v\n", val)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

Example (Batch)
package main

import (
	"context"
	"log"

	"github.com/openconfig/ygnmi/exampleoc"
	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Create a new batch object and add paths to it.
	b := new(exampleocpath.Batch)
	// Note: the AddPaths accepts paths not queries.
	b.AddPaths(exampleocpath.Root().RemoteContainer().ALeaf(), exampleocpath.Root().Model().SingleKeyAny().Value())
	// Watch all input path until they meet the desired condition.
	_, err := ygnmi.Watch(context.Background(), c, b.State(), func(v *ygnmi.Value[*exampleoc.Root]) error {
		val, ok := v.Val()
		if !ok {
			return ygnmi.Continue
		}
		if val.GetModel().GetSingleKey("foo").GetValue() == 1 && val.GetModel().GetSingleKey("bar").GetValue() == 2 &&
			val.GetRemoteContainer().GetALeaf() == "string" {

			return nil
		}
		return ygnmi.Continue
	}).Await()
	if err != nil {
		log.Fatalf("Failed to Watch: %v", err)
	}
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func WatchAll

func WatchAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], pred func(*Value[T]) error, opts ...Option) *Watcher[T]

WatchAll starts an asynchronous STREAM subscription, evaluating each observed value with the specified predicate. The predicate must return ygnmi.Continue to continue the Watch. To stop the Watch, return nil for a success or a non-nil error on failure. Watch can also be stopped by setting a deadline on or canceling the context. Calling Await on the returned Watcher waits for the subscription to complete. It returns the last observed value and a boolean that indicates whether that value satisfies the predicate.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/openconfig/ygnmi/exampleoc/exampleocpath"
	"github.com/openconfig/ygnmi/ygnmi"
)

func main() {
	c := initClient()
	// Watch a path
	path := exampleocpath.Root().Model().SingleKeyAny().Value()
	// Use a context with a timeout, so that Watch doesn't continue indefinitely.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	var gotKeyFoo, gotKeyBar bool
	// Watch list values and wait for 2 different list elements to be equal to 10.
	// Set ExampleWatch_batch for another way to use Watch will a wildcard query.
	watcher := ygnmi.WatchAll(ctx, c, path.State(), func(v *ygnmi.Value[int64]) error {
		if val, ok := v.Val(); ok {
			gotKeyFoo = gotKeyFoo || v.Path.GetElem()[2].Key["key"] == "foo" && val == 10
			gotKeyBar = gotKeyBar || v.Path.GetElem()[2].Key["key"] == "bar" && val == 10
		}

		// Return nil to indicate success and stop evaluating predicate.
		if gotKeyFoo && gotKeyBar {
			return nil
		}
		// Return ygnmi.Continue to continue evaluating the func.
		return ygnmi.Continue
	})
	// Child is the last value received.
	child, err := watcher.Await()
	if err != nil {
		log.Fatalf("Failed to Watch: %v", err)
	}
	// Check if the value is present.
	val, ok := child.Val()
	if !ok {
		log.Fatal("No value at path")
	}
	fmt.Printf("Last Value: %v\n", val)
}

func initClient() *ygnmi.Client {

	return nil
}
Output:

func (*Watcher[T]) Await

func (w *Watcher[T]) Await() (*Value[T], error)

Await waits for the watch to finish and returns the last received value and a boolean indicating whether the predicate evaluated to true. When Await returns the watcher is closed, and Await may not be called again.

type WildcardBatch added in v0.9.0

type WildcardBatch[T any] struct {
	// contains filtered or unexported fields
}

WildcardBatch contains a collection of paths. Calling Query() on the batch returns a query that can be used in LookupAll, WatchAll, etc on select paths within the root path.

func NewWildcardBatch added in v0.9.0

func NewWildcardBatch[T any](root WildcardQuery[T]) *WildcardBatch[T]

NewWildcardBatch creates a batch object. All paths in the batch must be children of the root query.

func (*WildcardBatch[T]) AddPaths added in v0.9.0

func (b *WildcardBatch[T]) AddPaths(paths ...UntypedQuery) error

AddPaths adds the paths to the batch. Paths must be children of the root.

func (*WildcardBatch[T]) Query added in v0.9.0

func (b *WildcardBatch[T]) Query() WildcardQuery[T]

Query returns a Query that can be used in gNMI operations. The returned query is immutable, adding paths does not modify existing queries.

type WildcardQuery

type WildcardQuery[T any] interface {
	AnyQuery[T]
	// IsWildcard restricts this interface to be used only where a wildcard path is expected.
	IsWildcard()
}

WildcardQuery is a wildcard gNMI query.

type WildcardQueryStruct added in v0.8.0

type WildcardQueryStruct[T any] struct {
	// contains filtered or unexported fields
}

WildcardQueryStruct is implementation of SingletonQuery interface for leaf nodes. Note: Do not use this type directly, instead use the generated Path API.

func NewWildcardQuery added in v0.8.0

func NewWildcardQuery[T any](goStructName string, state, shadowpath, leaf, scalar, compressedSchema, listContainer bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema, subPaths []PathStruct, compressInfo *CompressionInfo) *WildcardQueryStruct[T]

NewWildcardQuery creates a new NewLeafWildcardQuery object.

func (*WildcardQueryStruct) IsState added in v0.8.0

func (q *WildcardQueryStruct) IsState() bool

IsState returns if the Query is for a state or config path.

func (*WildcardQueryStruct[T]) IsWildcard added in v0.8.0

func (q *WildcardQueryStruct[T]) IsWildcard()

IsWildcard prevents this struct from being used where a non wildcard path is expected.

func (*WildcardQueryStruct) PathStruct added in v0.8.0

func (q *WildcardQueryStruct) PathStruct() PathStruct

PathStruct returns the path struct containing the path for the Query.

func (*WildcardQueryStruct) String added in v0.8.0

func (q *WildcardQueryStruct) String() string

String returns gNMI path as string for the query.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL