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
- func Bool(b bool) *bool
- func BuildEmptyTree(s GoStruct)
- func ConstructIETFJSON(s GoStruct, args *RFC7951JSONConfig) (map[string]interface{}, error)
- func ConstructInternalJSON(s GoStruct) (map[string]interface{}, error)
- func Diff(original, modified GoStruct, opts ...DiffOpt) (*gnmipb.Notification, error)
- func EmitJSON(s ValidatedGoStruct, opts *EmitJSONConfig) (string, error)
- func EncodeTypedValue(val interface{}, enc gnmipb.Encoding) (*gnmipb.TypedValue, error)
- func EnumName(e GoEnum) (string, error)
- func Float32(f float32) *float32
- func Float64(f float64) *float64
- func GzipToSchema(gzj []byte) (map[string]*yang.Entry, error)
- func InitContainer(s GoStruct, cname string) error
- func Int16(i int16) *int16
- func Int32(i int32) *int32
- func Int64(i int64) *int64
- func Int8(i int8) *int8
- func KeyValueAsString(v interface{}) (string, error)
- func MergeJSON(a, b map[string]interface{}) (map[string]interface{}, error)
- func MergeStructJSON(ns GoStruct, ej map[string]interface{}, opts *EmitJSONConfig) (map[string]interface{}, error)
- func PathKeyFromStruct(v reflect.Value) (map[string]string, error)
- func PathToSchemaPath(path *gnmipb.Path) (string, error)
- func PathToString(path *gnmipb.Path) (string, error)
- func PathToStrings(path *gnmipb.Path) ([]string, error)
- func PruneEmptyBranches(s GoStruct)
- func String(s string) *string
- func StringToPath(path string, pathTypes ...PathType) (*gnmipb.Path, error)
- func StringToStringSlicePath(path string) (*gnmipb.Path, error)
- func StringToStructuredPath(path string) (*gnmipb.Path, error)
- func ToPtr(v interface{}) interface{}
- func TogNMINotifications(s GoStruct, ts int64, cfg GNMINotificationsConfig) ([]*gnmipb.Notification, error)
- func Uint16(u uint16) *uint16
- func Uint32(u uint32) *uint32
- func Uint64(u uint64) *uint64
- func Uint8(u uint8) *uint8
- type Annotation
- type DiffOpt
- type DiffPathOpt
- type EmitJSONConfig
- type EnumDefinition
- type GNMINotificationsConfig
- type GoEnum
- type GoStruct
- type JSONFormat
- type KeyHelperGoStruct
- type PathType
- type RFC7951JSONConfig
- type ValidatedGoStruct
- type ValidationOption
Constants ¶
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 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 ¶
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 GzipToSchema ¶
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 ¶
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 KeyValueAsString ¶ added in v0.6.0
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 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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶
PathToString is like PathToStrings, but returns a single formatted string representing the path. Path is always treated as absolute.
func PathToStrings ¶
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 ¶ added in v0.6.0
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 StringToPath ¶
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 ¶
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 ¶
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 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.
Types ¶
type Annotation ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.6.0
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.
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 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.
Source Files ¶
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. |