Documentation ¶
Overview ¶
Package ygnmi contains gNMI client library for use with a ygot Schema.
Index ¶
- Constants
- Variables
- func BatchDelete[T any](sb *SetBatch, q ConfigQuery[T])
- func BatchReplace[T any](sb *SetBatch, q ConfigQuery[T], val T)
- func BatchUpdate[T any](sb *SetBatch, q ConfigQuery[T], val T)
- func Get[T any](ctx context.Context, c *Client, q SingletonQuery[T], opts ...Option) (T, error)
- func GetAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], opts ...Option) ([]T, error)
- func LatestRecvTimestamp(data []*DataPoint) time.Time
- func LatestTimestamp(data []*DataPoint) time.Time
- func ModifyKey(n *NodePath, name string, value interface{})
- func ResolvePath(n PathStruct) (*gpb.Path, map[string]interface{}, error)
- func ResolveRelPath(n PathStruct) ([]*gpb.PathElem, []error)
- type AnyQuery
- type Batch
- type Client
- type ClientOption
- type Collector
- type ComplianceErrors
- type ConfigQuery
- type DataPoint
- type DeviceRootBase
- type ExtractFn
- type LeafConfigQuery
- type LeafSingletonQuery
- type LeafWildcardQuery
- type NodePath
- type NonLeafConfigQuery
- type NonLeafSingletonQuery
- type NonLeafWildcardQuery
- type Option
- type PathStruct
- type Result
- func Delete[T any](ctx context.Context, c *Client, q ConfigQuery[T], opts ...Option) (*Result, error)
- func Replace[T any](ctx context.Context, c *Client, q ConfigQuery[T], val T, opts ...Option) (*Result, error)
- func Update[T any](ctx context.Context, c *Client, q ConfigQuery[T], val T, opts ...Option) (*Result, error)
- type SetBatch
- type SingletonQuery
- type TelemetryError
- type Value
- func Await[T any](ctx context.Context, c *Client, q SingletonQuery[T], val T, opts ...Option) (*Value[T], error)
- func Lookup[T any](ctx context.Context, c *Client, q SingletonQuery[T], opts ...Option) (*Value[T], error)
- func LookupAll[T any](ctx context.Context, c *Client, q WildcardQuery[T], opts ...Option) ([]*Value[T], error)
- type Watcher
- type WildcardQuery
Examples ¶
Constants ¶
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" )
const (
// OriginOverride is the key to custom opt that sets the path origin.
OriginOverride = "origin-override"
)
Variables ¶
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 an update operation in the SetBatch.
func BatchReplace ¶
func BatchReplace[T any](sb *SetBatch, q ConfigQuery[T], val T)
BatchReplace stores an update operation in the SetBatch.
func BatchUpdate ¶
func BatchUpdate[T any](sb *SetBatch, q ConfigQuery[T], val T)
BatchUpdate stores an update operation in the SetBatch.
func Get ¶
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 ¶
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 ¶
LatestRecvTimestamp returns the latest recv timestamp of the input datapoints. If datapoints is empty, then the zero time is returned.
func LatestTimestamp ¶
LatestTimestamp returns the latest timestamp of the input datapoints. If datapoints is empty, then the zero time is returned.
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 { // 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 }
AnyQuery is a generic gNMI query for wildcard or non-wildcard state or config paths. Supported operations: Batch.
type Batch ¶
type Batch[T ygot.ValidatedGoStruct] 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 ¶
func NewBatch[T ygot.ValidatedGoStruct](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 ¶
func (b *Batch[T]) AddPaths(paths ...PathStruct) error
AddPaths adds the paths to the batch. Paths must be children of the root.
func (*Batch[T]) Query ¶
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.
type ClientOption ¶
ClientOption configures a client with custom options.
func WithRequestLogLevel ¶
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:
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 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 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.
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 LeafConfigQuery ¶
type LeafConfigQuery[T any] struct { // contains filtered or unexported fields }
LeafConfigQuery is implementation of ConfigQuery interface for leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewLeafConfigQuery ¶
func NewLeafConfigQuery[T any](parentDir string, state, scalar bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema) *LeafConfigQuery[T]
NewLeafConfigQuery creates a new NewLeafConfigQuery object.
func (*LeafConfigQuery[T]) IsConfig ¶
func (lq *LeafConfigQuery[T]) IsConfig()
IsConfig restricts this struct to be used only where a config path is expected.
func (*LeafConfigQuery[T]) IsSingleton ¶
func (lq *LeafConfigQuery[T]) IsSingleton()
IsSingleton restricts this struct to be used only where a singleton path is expected.
func (*LeafConfigQuery) IsState ¶
func (lq *LeafConfigQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*LeafConfigQuery) PathStruct ¶
func (lq *LeafConfigQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
type LeafSingletonQuery ¶
type LeafSingletonQuery[T any] struct { // contains filtered or unexported fields }
LeafSingletonQuery is implementation of SingletonQuery interface for leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewLeafSingletonQuery ¶
func NewLeafSingletonQuery[T any](parentDir string, state, scalar bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema) *LeafSingletonQuery[T]
NewLeafSingletonQuery creates a new LeafSingletonQuery object.
func (*LeafSingletonQuery[T]) IsSingleton ¶
func (lq *LeafSingletonQuery[T]) IsSingleton()
IsSingleton prevents this struct from being used where a wildcard path is expected.
func (*LeafSingletonQuery) IsState ¶
func (lq *LeafSingletonQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*LeafSingletonQuery) PathStruct ¶
func (lq *LeafSingletonQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
type LeafWildcardQuery ¶
type LeafWildcardQuery[T any] struct { // contains filtered or unexported fields }
LeafWildcardQuery is implementation of SingletonQuery interface for leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewLeafWildcardQuery ¶
func NewLeafWildcardQuery[T any](parentDir string, state, scalar bool, ps PathStruct, extractFn ExtractFn[T], goStructFn func() ygot.ValidatedGoStruct, schemaFn func() *ytypes.Schema) *LeafWildcardQuery[T]
NewLeafWildcardQuery creates a new NewLeafWildcardQuery object.
func (*LeafWildcardQuery) IsState ¶
func (lq *LeafWildcardQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*LeafWildcardQuery[T]) IsWildcard ¶
func (lq *LeafWildcardQuery[T]) IsWildcard()
IsWildcard prevents this struct from being used where a non wildcard path is expected.
func (*LeafWildcardQuery) PathStruct ¶
func (lq *LeafWildcardQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
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 NonLeafConfigQuery ¶
type NonLeafConfigQuery[T ygot.ValidatedGoStruct] struct { // contains filtered or unexported fields }
NonLeafConfigQuery is implementation of ConfigQuery interface for non-leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewNonLeafConfigQuery ¶
func NewNonLeafConfigQuery[T ygot.ValidatedGoStruct](dir string, state bool, ps PathStruct, subPaths []PathStruct, schemaFn func() *ytypes.Schema) *NonLeafConfigQuery[T]
NewNonLeafConfigQuery creates a new NewNonLeafConfigQuery object.
func (*NonLeafConfigQuery[T]) IsConfig ¶
func (nlq *NonLeafConfigQuery[T]) IsConfig()
IsConfig restricts this struct to be used only where a config path is expected.
func (*NonLeafConfigQuery[T]) IsSingleton ¶
func (nlq *NonLeafConfigQuery[T]) IsSingleton()
IsSingleton restricts this struct to be used only where a singleton path is expected.
func (*NonLeafConfigQuery) IsState ¶
func (lq *NonLeafConfigQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*NonLeafConfigQuery) PathStruct ¶
func (lq *NonLeafConfigQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
type NonLeafSingletonQuery ¶
type NonLeafSingletonQuery[T ygot.ValidatedGoStruct] struct { // contains filtered or unexported fields }
NonLeafSingletonQuery is implementation of SingletonQuery interface for non-leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewNonLeafSingletonQuery ¶
func NewNonLeafSingletonQuery[T ygot.ValidatedGoStruct](dir string, state bool, ps PathStruct, subPaths []PathStruct, schemaFn func() *ytypes.Schema) *NonLeafSingletonQuery[T]
NewNonLeafSingletonQuery creates a new NonLeafSingletonQuery object.
func (*NonLeafSingletonQuery[T]) IsSingleton ¶
func (lq *NonLeafSingletonQuery[T]) IsSingleton()
IsSingleton prevents this struct from being used where a wildcard path is expected.
func (*NonLeafSingletonQuery) IsState ¶
func (lq *NonLeafSingletonQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*NonLeafSingletonQuery) PathStruct ¶
func (lq *NonLeafSingletonQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
type NonLeafWildcardQuery ¶
type NonLeafWildcardQuery[T ygot.ValidatedGoStruct] struct { // contains filtered or unexported fields }
NonLeafWildcardQuery is implementation of SingletonQuery interface for non-leaf nodes. Note: Do not use this type directly, instead use the generated Path API.
func NewNonLeafWildcardQuery ¶
func NewNonLeafWildcardQuery[T ygot.ValidatedGoStruct](dir string, state bool, ps PathStruct, schemaFn func() *ytypes.Schema) *NonLeafWildcardQuery[T]
NewNonLeafWildcardQuery creates a new NewNonLeafWildcardQuery object.
func (*NonLeafWildcardQuery) IsState ¶
func (lq *NonLeafWildcardQuery) IsState() bool
IsState returns if the Query is for a state or config path.
func (*NonLeafWildcardQuery[T]) IsWildcard ¶
func (lq *NonLeafWildcardQuery[T]) IsWildcard()
IsWildcard prevents this struct from being used where a non-wildcard path is expected.
func (*NonLeafWildcardQuery) PathStruct ¶
func (lq *NonLeafWildcardQuery) PathStruct() PathStruct
PathStruct returns the path struct containing the path for the Query.
type Option ¶
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 ¶
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 WithSetFallbackEncoding ¶
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 ¶
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 ¶
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.
func WithUseGet ¶
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 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 ¶
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 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 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:
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:
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.