ygot

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2019 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package ygot contains helper methods for dealing with structs that represent a YANG schema. Particularly, it takes structs that represent a YANG schema - generated by ygen:

  • Provides helper functions which simplify their usage such as functions to return pointers to a type.
  • Renders structs to other output formats such as JSON, or gNMI notifications.

Index

Constants

View Source
const (
	// BinaryTypeName is the name of the type that is used for YANG
	// binary fields in the output structs.
	BinaryTypeName string = "Binary"
	// EmptyTypeName is the name of the type that is used for YANG
	// empty fields in the output structs.
	EmptyTypeName string = "YANGEmpty"
)

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool takes a boolean argument and returns a pointer to it.

func BuildEmptyTree

func BuildEmptyTree(s GoStruct)

BuildEmptyTree initialises the YANG tree starting at the root GoStruct provided. This allows the YANG container hierarchy (i.e., any structs within the tree) to be pre-initialised rather than requiring the user to initialise each as it is required. Given that some trees may be large, then some caution should be exercised in initialising an entire tree. If struct pointer fields are non-nil, they are considered initialised, and are skipped.

func ConstructIETFJSON

func ConstructIETFJSON(s GoStruct, args *RFC7951JSONConfig) (map[string]interface{}, error)

ConstructIETFJSON marshals a supplied GoStruct to a map, suitable for handing to json.Marshal. It complies with the convention for marshalling to JSON described by RFC7951. The appendModName argument determines whether the module name should be appended to entities that are defined in a different module to their parent.

func ConstructInternalJSON

func ConstructInternalJSON(s GoStruct) (map[string]interface{}, error)

ConstructInternalJSON marshals a supplied GoStruct to a map, suitable for handing to json.Marshal. It uses the loosely specified JSON format document in go/yang-internal-json.

func Diff

func Diff(original, modified GoStruct, opts ...DiffOpt) (*gnmipb.Notification, error)

Diff takes an original and modified GoStruct, which must be of the same type and returns a gNMI Notification that contains the diff between them. The original struct is considered as the "from" data, with the modified struct the "to" such that:

  • The contents of the Update field of the notification indicate that the field in modified was either not present in original, or had a different field value.
  • The paths within the Delete field of the notification indicate that the field was not present in the modified struct, but was set in the original.

Annotation fields that are contained within the supplied original or modified GoStruct are skipped.

A set of options for diff's behaviour, as specified by the supplied DiffOpts can be used to modify the behaviour of the Diff function per the individual option's specification.

The returned gNMI Notification cannot be put on the wire unmodified, since it does not specify a timestamp - and may not contain the absolute paths to the fields specified if a GoStruct that does not represent the root of a YANG schema tree is not supplied as original and modified.

func EmitJSON

func EmitJSON(s ValidatedGoStruct, opts *EmitJSONConfig) (string, error)

EmitJSON takes an input ValidatedGoStruct (produced by ygen with validation enabled) and serialises it to a JSON string. By default, produces the Internal format JSON.

func EncodeTypedValue

func EncodeTypedValue(val interface{}, enc gnmipb.Encoding) (*gnmipb.TypedValue, error)

EncodeTypedValue encodes val into a gNMI TypedValue message, using the specified encoding type if the value is a struct.

func EnumName

func EnumName(e GoEnum) (string, error)

EnumName returns the string name of an input GoEnum e. If the enumeration is unset, the name returned is an empty string, otherwise it is the name defined within the YANG schema.

func Float32

func Float32(f float32) *float32

Float32 takes a float32 argument and returns a pointer to it.

func Float64

func Float64(f float64) *float64

Float64 takes a float64 argument and returns a pointer to it.

func GzipToSchema

func GzipToSchema(gzj []byte) (map[string]*yang.Entry, error)

GzipToSchema takes an input byte slice, and returns it as a map of yang.Entry nodes, keyed by the name of the struct that the yang.Entry describes the schema for.

func InitContainer

func InitContainer(s GoStruct, cname string) error

InitContainer initialises the container cname of the GoStruct s, it can be used to initialise an arbitrary named child container within a YANG structure in a generic manner. This allows the caller to generically initialise a sub-element of the YANG tree without needing to have specific handling code.

func Int16

func Int16(i int16) *int16

Int16 takes an int16 argument and returns a pointer to it.

func Int32

func Int32(i int32) *int32

Int32 takes an int32 argument and returns a pointer to it.

func Int64

func Int64(i int64) *int64

Int64 takes an int64 argument and returns a pointer to it.

func Int8

func Int8(i int8) *int8

Int8 takes an int8 argument and returns a pointer to it.

func KeyValueAsString

func KeyValueAsString(v interface{}) (string, error)

KeyValueAsString returns a string representation of the interface{} supplied. If the type provided cannot be represented as a string for use in a gNMI path, an error is returned.

func MergeJSON

func MergeJSON(a, b map[string]interface{}) (map[string]interface{}, error)

MergeJSON takes two input maps, and merges them into a single map.

func MergeStructJSON

func MergeStructJSON(ns GoStruct, ej map[string]interface{}, opts *EmitJSONConfig) (map[string]interface{}, error)

MergeStructJSON marshals the GoStruct ns to JSON according to the configuration, and merges it with the existing JSON provided as a map[string]interface{}. The merged JSON output is returned.

To create valid JSON-serialised YANG, it is expected that the existing JSON is in the same format as is specified in the options. Where there are overlapping tree elements in the serialised struct they are merged where possible.

func PathKeyFromStruct

func PathKeyFromStruct(v reflect.Value) (map[string]string, error)

PathKeyFromStruct returns a map[string]string which represents the keys for a YANG list element. The provided reflect.Value must implement the KeyHelperGoStruct interface, and hence be a struct which represents a list member within the schema.

func PathToSchemaPath

func PathToSchemaPath(path *gnmipb.Path) (string, error)

PathToSchemaPath returns the supplied Path as its corresponding schema path. The YANG schema path removes any keys (i.e., predicates) from the path, using only the name.

func PathToString

func PathToString(path *gnmipb.Path) (string, error)

PathToString is like PathToStrings, but returns a single formatted string representing the path. Path is always treated as absolute.

func PathToStrings

func PathToStrings(path *gnmipb.Path) ([]string, error)

PathToStrings takes a gNMI Path and provides its string representation. For example, the path Path{Element: []string{"one", "two", "three"} is converted to the slice ["one", "two", "three"] and returned. Both the pre-0.4.0 "element"-based paths, and the

>0.4.0 paths based on "elem" are supported. In the case that post-0.4.0 paths are

specified, keys that are specified in the path are concatenated onto the name of the path element using the format [name=value]. If the path specifies both pre- and post-0.4.0 paths, the pre-0.4.0 version is returned.

func PruneEmptyBranches

func PruneEmptyBranches(s GoStruct)

PruneEmptyBranches removes branches that have no populated children from the GoStruct s in-place. This allows a YANG container hierarchy that has been initialised with BuildEmptyTree to have those branches that were not populated removed from the tree. All subtrees rooted at the supplied GoStruct are traversed and any encountered GoStruct pointer fields are removed if they equate to the zero value (i.e. are unpopulated).

func String

func String(s string) *string

String takes a string argument and returns a pointer to it.

func StringToPath

func StringToPath(path string, pathTypes ...PathType) (*gnmipb.Path, error)

StringToPath takes an input string representing a path in gNMI, and converts it to a gNMI Path message, populated with the specified path encodings.

func StringToStringSlicePath

func StringToStringSlicePath(path string) (*gnmipb.Path, error)

StringToStringSlicePath takes a string representing a path, and converts it into a gnmi.Path. For example, if the Path "/a/b[c=d]/e" is input, it is converted to a gnmi.Path{Element: []string{"a", "b[c=d]", "e"}} which is returned. Where there are complex predicates that are used within an element, they are not parsed and the contents is left unchanged. This implements the legacy string slice path that are used in gNMI pre-0.4.0. The specification for these paths is at https://goo.gl/uD6g6z.

func StringToStructuredPath

func StringToStructuredPath(path string) (*gnmipb.Path, error)

StringToStructuredPath takes a string representing a path, and converts it to a gnmi.Path, using the PathElem element message that is defined in gNMI 0.4.0.

func ToPtr

func ToPtr(v interface{}) interface{}

ToPtr returns a pointer to v.

func TogNMINotifications

func TogNMINotifications(s GoStruct, ts int64, cfg GNMINotificationsConfig) ([]*gnmipb.Notification, error)

TogNMINotifications takes an input GoStruct and renders it to slice of Notification messages, marked with the specified timestamp. The configuration provided determines the path format utilised, and the prefix to be included in the message if relevant.

TODO(robjs): When we have deprecated the string slice paths, then this function can be simplified to remove support for them - including removing the gnmiPath abstraction. It can also be refactored to simply use the findSetleaves function which has a cleaner implementation using the reworked iterfunction util.

func Uint16

func Uint16(u uint16) *uint16

Uint16 takes an uint16 argument and returns a pointer to it.

func Uint32

func Uint32(u uint32) *uint32

Uint32 takes an uint32 argument and returns a pointer to it.

func Uint64

func Uint64(u uint64) *uint64

Uint64 takes an uint64 argument and returns a pointer to it.

func Uint8

func Uint8(u uint8) *uint8

Uint8 takes an uint8 argument and returns a pointer to it.

Types

type Annotation

type Annotation interface {
	// MarshalJSON is used to marshal the annotation to JSON. It ensures that
	// the json.Marshaler interface is implemented.
	MarshalJSON() ([]byte, error)
	// UnmarshalJSON is used to unmarshal JSON into the Annotation. It ensures that
	// the json.Unmarshaler interface is implemented.
	UnmarshalJSON([]byte) error
}

Annotation defines an interface that is implemented by optional metadata fields within a GoStruct. Annotations are stored within each struct, and for a struct field, for example:

type GoStructExample struct {
   ΛMetadata []*ygot.Annotation `path:"@"`
   StringField *string `path:"string-field"`
   ΛStringField []*ygot.Annotation `path:"@string-field"`
}

The ΛMetadata and ΛStringField fields can be populated with a slice of arbitrary types implementing the Annotation interface.

Each Annotation must implement the MarshalJSON and UnmarshalJSON methods, such that its content can be serialised and deserialised from JSON. Using the approach described in RFC7952 can be used to store metadata within RFC7951-serialised JSON.

type DiffOpt

type DiffOpt interface {
	// IsDiffOpt is a marker method for each DiffOpt.
	IsDiffOpt()
}

DiffOpt is an interface that is implemented by the options to the Diff function. It allows user specified options to be propagated to the diff method.

type DiffPathOpt

type DiffPathOpt struct {
	// MapToSinglePath specifies whether a single ygot.GoStruct field should
	// be mapped to more than one value. If set to true, when a struct tag
	// annotation specifies more than one path (e.g., `path:"foo|config/foo"`)
	// only the shortest path is mapped to.
	//
	// This option is primarily used where path compression has been used in the
	// generated structs, which can result in duplication of list key leaves in
	// the diff output.
	MapToSinglePath bool
}

DiffPathOpt is a DiffOpt that allows control of the path behaviour of the Diff function.

func (*DiffPathOpt) IsDiffOpt

func (*DiffPathOpt) IsDiffOpt()

IsDiffOpt marks DiffPathOpt as a diff option.

type EmitJSONConfig

type EmitJSONConfig struct {
	// Format specifies the JSON format that should be output by the EmitJSON
	// function - using the enumerated JSONType function. By default, internal
	// format JSON will be produced.
	Format JSONFormat
	// RFC7951Config specifies the configuration options for RFC7951 JSON. Only
	// valid if Format is RFC7951.
	RFC7951Config *RFC7951JSONConfig
	// Indent is the string used for indentation within the JSON output. The
	// default value is three spaces.
	Indent string
	// SkipValidation specifies whether the GoStruct supplied to EmitJSON should
	// be validated before emitting its content. Validation is skipped when it
	// is set to true.
	SkipValidation bool
	// ValidationOpts is the set of options that should be used to determine how
	// the schema should be validated. This allows fine-grained control of particular
	// validation rules in the case that a partially populated data instance is
	// to be emitted.
	ValidationOpts []ValidationOption
}

EmitJSONConfig specifies the how JSON should be created by the EmitJSON function.

type EnumDefinition

type EnumDefinition struct {
	// Name is the string name of the enumerated value.
	Name string
	// DefiningModule specifies the module within which the enumeration was
	// defined. Only populated for identity values.
	DefiningModule string
}

EnumDefinition is used to store the details of an enumerated value. All YANG enumerated values (enumeration, identityref) has a Name which represents the string name used for the enumerated value in the YANG module (which may not be Go safe). Enumerated types that are derived from identity values also have an associated DefiningModule, such that they can be serialised to the correct RFC7951 JSON format (see Section 6.8 of RFC7951), https://tools.ietf.org/html/rfc7951#section-6.8

type GNMINotificationsConfig

type GNMINotificationsConfig struct {
	// UsePathElem specifies whether the elem field of the gNMI Path
	// message should be used for the paths in the output notification. If
	// set to false, the element field is used.
	UsePathElem bool
	// ElementPrefix stores the prefix that should be used within the
	// Prefix field of the gNMI Notification message expressed as a slice
	// of strings as per the path definition in gNMI 0.3.1 and below.
	// Used if UsePathElem is unset.
	StringSlicePrefix []string
	// PathElemPrefix stores the prefix that should be used withinthe
	// Prefix field of the gNMI Notification message, expressed as a slice
	// of PathElem messages. This path format is used by gNMI 0.4.0 and
	// above. Used if PathElem is set.
	PathElemPrefix []*gnmipb.PathElem
}

GNMINotificationsConfig specifies arguments determining how the gNMI output should be created by ygot.

type GoEnum

type GoEnum interface {
	// IsYANGGoEnum is a marker method that indicates that the
	// struct implements the GoEnum interface.
	IsYANGGoEnum()
	// ΛMap is a method associated with each enumeration that retrieves a
	// map of the enumeration types to values that are associated with a
	// generated code file. The ygen library generates a static map of
	// enumeration values that this method returns.
	ΛMap() map[string]map[int64]EnumDefinition
}

GoEnum is an interface which can be implemented by derived types which represent an enumerated value within a YANG schema. This allows handling code that finds struct fields that implement this interface to do specific mapping to other types when translating to a particular schematree.

type GoStruct

type GoStruct interface {
	// IsYANGGoStruct is a marker method that indicates that the struct
	// implements the GoStruct interface.
	IsYANGGoStruct()
}

GoStruct is an interface which can be implemented by Go structs that are generated to represent a YANG container or list member. It simply allows handling code to ensure that it is interacting with a struct that will meet the expectations of the interface - such as the fields being tagged with appropriate metadata (tags) that allow mapping of the struct into a YANG schematree.

func DeepCopy

func DeepCopy(s GoStruct) (GoStruct, error)

DeepCopy returns a deep copy of the supplied GoStruct. A new copy of the GoStruct is created, along with any underlying values.

type JSONFormat

type JSONFormat int

JSONFormat is an enumerated integer value indicating the JSON format.

const (
	// Internal is the custom JSON format that is output by the validation library, and
	// by pyangbind. It is loosely specified - but is the default used by generator developers.
	Internal JSONFormat = iota
	// RFC7951 is JSON that conforms to RFC7951.
	RFC7951
)

type KeyHelperGoStruct

type KeyHelperGoStruct interface {
	// GoStruct ensures that the interface for a standard GoStruct
	// is embedded.
	GoStruct
	// ΛListKeyMap defines a helper method that returns a map of the
	// keys of a list element.
	ΛListKeyMap() (map[string]interface{}, error)
}

KeyHelperGoStruct is an interface which can be implemented by Go structs that are generated to represent a YANG container or list member that has the corresponding function to retrieve the list keys as a map.

type PathType

type PathType int64

PathType is used to indicate a gNMI path type.

const (
	// StructuredPath represents a Path using the structured 'PathElem' message in
	// the 'elem' field of the gNMI Path message.
	StructuredPath PathType = iota
	// StringSlicePath represents a Path using the 'Element' repeated string field
	// of the gNMI path message.
	StringSlicePath
)

type RFC7951JSONConfig

type RFC7951JSONConfig struct {
	// AppendModuleName determines whether the module name is appended to
	// elements that are defined within a different YANG module than their
	// parent.
	AppendModuleName bool
}

RFC7951JSONConfig is used to control the behaviour of how RFC7951 JSON is output by the ygot library.

type ValidatedGoStruct

type ValidatedGoStruct interface {
	// GoStruct ensures that the interface for a standard GoStruct
	// is embedded.
	GoStruct
	// Validate compares the contents of the implementing struct against
	// the YANG schema, and returns an error if the struct's contents
	// are not valid, or nil if the struct complies with the schema.
	Validate(...ValidationOption) error
	// ΛEnumTypeMap returns the set of enumerated types that are contained
	// in the generated code.
	ΛEnumTypeMap() map[string][]reflect.Type
}

ValidatedGoStruct is an interface which can be implemented by Go structs that are generated to represent a YANG container or list member that have the corresponding function to be validated against the a YANG schema.

func MergeStructs

func MergeStructs(a, b ValidatedGoStruct) (ValidatedGoStruct, error)

MergeStructs takes two input ValidatedGoStructs and merges their contents, returning a new ValidatedGoStruct. If the input structs a and b are of different types, an error is returned.

Where two structs contain maps or slices that are populated in both a and b their contents are merged. If a leaf is populated in both a and b, an error is returned if the value of the leaf is not equal.

type ValidationOption

type ValidationOption interface {
	IsValidationOption()
}

ValidationOption is an interface that is implemented for each struct which presents configuration parameters for validation options through the Validate public API.

Directories

Path Synopsis
Package pathtranslate exports api to transform given string slice into different forms in a schema aware manner.
Package pathtranslate exports api to transform given string slice into different forms in a schema aware manner.
Package schematest is used for testing with the default OpenConfig generated structs.
Package schematest is used for testing with the default OpenConfig generated structs.

Jump to

Keyboard shortcuts

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