Newer
Older
import (
"fmt"
"strconv"
"time"
ppb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd"
"code.fbi.h-da.de/danet/gosdn/controller/customerrs"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
gpb "github.com/openconfig/gnmi/proto/gnmi"
gnmiv "github.com/openconfig/gnmi/value"
"github.com/openconfig/goyang/pkg/yang"
"github.com/openconfig/ygot/ygot"
"github.com/openconfig/ygot/ytypes"
log "github.com/sirupsen/logrus"
)
type DeviceModel struct {
model ygot.ValidatedGoStruct
schema *ytypes.Schema
generatedUnmarshalFn func([]byte, ygot.GoStruct, ...ytypes.UnmarshalOpt) error
genereatedSchemaTreeGzipFn func() []byte
func NewDeviceModel(generatedSchemaFn func() (*ytypes.Schema, error), generatedUnmarshalFn func([]byte, ygot.GoStruct, ...ytypes.UnmarshalOpt) error, genereatedSchemaTreeGzipFn func() []byte) (*DeviceModel, error) {
schema, err := generatedSchemaFn()
if err != nil {
return nil, err
}
validatedCopy, err := createValidatedCopy(schema.Root)
if err != nil {
return nil, err
}
return &DeviceModel{
model: validatedCopy,
schema: schema,
generatedUnmarshalFn: generatedUnmarshalFn,
genereatedSchemaTreeGzipFn: genereatedSchemaTreeGzipFn,
// Unmarshal takes a JSON as []byte and parses it into the DeviceModels GoStruct.
func (d *DeviceModel) Unmarshal(json []byte, path *gpb.Path) error {
opts := []ytypes.UnmarshalOpt{&ytypes.IgnoreExtraFields{}}
return unmarshal(d.schema, d.generatedUnmarshalFn, json, path, d.model, opts...)
}
// unmarshal parses a gNMI response to a go struct.
func unmarshal(
schema *ytypes.Schema,
generatedUnmarshalFn func([]byte, ygot.GoStruct, ...ytypes.UnmarshalOpt) error,
bytes []byte,
path *gpb.Path,
goStruct ygot.GoStruct,
opt ...ytypes.UnmarshalOpt) error {
defer func() {
if r := recover(); r != nil {
log.Error(r.(error))
}
}()
validatedDeepCopy, err := createValidatedCopy(schema.Root)
if err != nil {
return err
}
// returns the node we want to fill with the data contained in 'bytes',
// using the specified 'path'.
createdNode, _, err := ytypes.GetOrCreateNode(schema.RootSchema(), validatedDeepCopy, path)
if err != nil {
return err
}
validatedCreatedNode, ok := createdNode.(ygot.ValidatedGoStruct)
if !ok {
return &customerrs.InvalidTypeAssertionError{
Value: createdNode,
Type: (*ygot.ValidatedGoStruct)(nil),
}
}
if err := generatedUnmarshalFn(bytes, validatedCreatedNode, opt...); err != nil {
return err
}
opts := []ygot.MergeOpt{&ygot.MergeOverwriteExistingFields{}}
return ygot.MergeStructInto(goStruct, validatedDeepCopy, opts...)
}
// SetNode sets the current Node within the given ygot.GoStruct with the value
// provided at the given path.
func (d *DeviceModel) SetNode(path *gpb.Path, value *gpb.TypedValue) error {
opts := []ytypes.SetNodeOpt{&ytypes.InitMissingElements{}, &ytypes.TolerateJSONInconsistencies{}}
return ytypes.SetNode(d.schema.RootSchema(), d.model, path, value, opts...)
}
// DeleteNode deletes the current Node within the given ygot.GoStruct at the
// given path.
func (d *DeviceModel) DeleteNode(path *gpb.Path) error {
opts := []ytypes.DelNodeOpt{}
return ytypes.DeleteNode(d.schema.RootSchema(), d.model, path, opts...)
}
func (d *DeviceModel) GetNode(path *gpb.Path) ([]*gpb.Notification, error) {
opts := []ytypes.GetNodeOpt{&ytypes.GetHandleWildcards{}, &ytypes.GetPartialKeyMatch{}}
nodes, err := ytypes.GetNode(d.schema.RootSchema(), d.model, path, opts...)
if err != nil {
return nil, err
}
Malte Bauch
committed
notifications := make([]*gpb.Notification, len(nodes))
Malte Bauch
committed
generatedNotifictaions, err := genGnmiNotification(path, node.Data)
if err != nil {
return nil, status.Errorf(codes.Aborted, "%v", err)
}
Malte Bauch
committed
notifications[i] = generatedNotifictaions
Malte Bauch
committed
return notifications, nil
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
}
func genGnmiNotification(path *gpb.Path, val any) (*gpb.Notification, error) {
typedVal, err := ygot.EncodeTypedValue(val, gpb.Encoding_JSON_IETF)
if err != nil {
return nil, err
}
return &gpb.Notification{
Timestamp: time.Now().UnixNano(),
Update: []*gpb.Update{
{
Path: &gpb.Path{
Elem: path.GetElem(),
},
Val: typedVal,
},
},
}, nil
}
// Model returns the current model as byte slice representing a JSON.
func (d *DeviceModel) Model() ([]byte, error) {
return ygot.Marshal7951(d.model, getYgotMarshal7951Config(), ygot.JSONIndent(""))
}
// SchemaTree returns the gzipped version of the SchemaTree as byte slice.
func (d *DeviceModel) SchemaTreeGzip() ([]byte, error) {
return d.genereatedSchemaTreeGzipFn(), nil
}
// Diff returns the difference of two DeviceModels based on their JSON
// representation.
func (d *DeviceModel) Diff(original, modified []byte) (*gpb.Notification, error) {
opts := []ytypes.UnmarshalOpt{&ytypes.IgnoreExtraFields{}}
originalAsValidatedCopy, err := createValidatedCopy(d.schema.Root)
if err != nil {
return nil, err
}
modifiedAsValidatedCopy, err := createValidatedCopy(d.schema.Root)
if err != nil {
return nil, err
}
if err := d.generatedUnmarshalFn(original, originalAsValidatedCopy, opts...); err != nil {
if err := d.generatedUnmarshalFn(modified, modifiedAsValidatedCopy, opts...); err != nil {
//TODO: This should be changed to be optional
ygot.PruneConfigFalse(d.schema.RootSchema(), originalAsValidatedCopy)
ygot.PruneConfigFalse(d.schema.RootSchema(), modifiedAsValidatedCopy)
return ygot.Diff(originalAsValidatedCopy, modifiedAsValidatedCopy)
}
func (d *DeviceModel) ValidateChange(operation ppb.ApiOperation, path *gpb.Path, value []byte) ([]byte, error) {
modelCopy, err := createValidatedCopy(d.model)
if err != nil {
return nil, err
}
switch operation {
case ppb.ApiOperation_API_OPERATION_UPDATE, ppb.ApiOperation_API_OPERATION_REPLACE:
_, entry, err := ytypes.GetOrCreateNode(d.schema.RootSchema(), modelCopy, path)
if err != nil {
return nil, err
}
if entry.IsDir() {
opts := []ytypes.UnmarshalOpt{&ytypes.IgnoreExtraFields{}}
if err := d.generatedUnmarshalFn(value, modelCopy, opts...); err != nil {
return nil, err
}
} else if entry.IsLeaf() {
typedValue, err := convertStringToGnmiTypedValue(string(value), entry.Type)
if err != nil {
return nil, err
}
opts := []ytypes.SetNodeOpt{&ytypes.InitMissingElements{}, &ytypes.TolerateJSONInconsistencies{}}
if err := ytypes.SetNode(d.schema.RootSchema(), modelCopy, path, typedValue, opts...); err != nil {
return nil, err
}
}
case ppb.ApiOperation_API_OPERATION_DELETE:
if err := ytypes.DeleteNode(d.schema.RootSchema(), modelCopy, path); err != nil {
return nil, err
}
default:
return nil, &customerrs.OperationNotSupportedError{Op: operation}
}
ygot.PruneEmptyBranches(modelCopy)
return ygot.Marshal7951(modelCopy, getYgotMarshal7951Config(), ygot.JSONIndent(""))
}
Malte Bauch
committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//TODO: add PruneConfigFalse for the plugin; e.g., filtered copy
////remove read-only fields
//err = ygot.PruneConfigFalse(schema.RootSchema(), validatedCpy)
//if err != nil {
// return uuid.Nil, err
//}
//func createFilteredCopy(n networkelement.NetworkElement) (ygot.GoStruct, error) {
// modelCopy, err := n.CreateModelCopy()
// if err != nil {
// return nil, err
// }
//
// schema, err := n.SBI().Schema()
// if err != nil {
// return nil, err
// }
//
// //remove read-only fields
// err = ygot.PruneConfigFalse(schema.RootSchema(), modelCopy)
// if err != nil {
// return nil, err
// }
//
// return modelCopy, nil
//}
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// convertStringToGnmiTypedValue allows to convert a string into a
// gnmi.TypedValue; this conversion is based on the provided YANG type.
func convertStringToGnmiTypedValue(s string, t *yang.YangType) (*gpb.TypedValue, error) {
// TODO: add more types
switch t.Kind {
case yang.Yint8, yang.Yint16, yang.Yint32, yang.Yint64:
return convertStringToIntTypedValue(s)
case yang.Yuint8, yang.Yuint16, yang.Yuint32, yang.Yuint64:
return convertStringToUintTypedValue(s)
case yang.Ybool:
parsedBool, err := strconv.ParseBool(s)
if err != nil {
return nil, err
}
return gnmiv.FromScalar(parsedBool)
case yang.Ystring:
return gnmiv.FromScalar(s)
default:
return nil, fmt.Errorf("could not convert to TypedValue, unsupported type of: %v", t)
}
}
func convertStringToIntTypedValue(s string) (*gpb.TypedValue, error) {
parsedInt, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return nil, err
}
return &gpb.TypedValue{
Value: &gpb.TypedValue_IntVal{
IntVal: int64(parsedInt),
},
}, nil
}
func convertStringToUintTypedValue(s string) (*gpb.TypedValue, error) {
parsedInt, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
return &gpb.TypedValue{
Value: &gpb.TypedValue_UintVal{
UintVal: uint64(parsedInt),
},
}, nil
}
// createValidatedCopy is a helper function which returns a validated
// copy of the `Device` struct.
func createValidatedCopy(toCopy ygot.GoStruct) (ygot.ValidatedGoStruct, error) {
// create a deep copy of the schema's root
schemaRootCopy, err := ygot.DeepCopy(toCopy)
if err != nil {
return nil, err
}
//ygot.BuildEmptyTree(schemaRootCopy)
validatedCopy, ok := schemaRootCopy.(ygot.ValidatedGoStruct)
if !ok {
return nil, customerrs.InvalidTypeAssertionError{
Value: validatedCopy,
Type: (*ygot.ValidatedGoStruct)(nil),
}
}
return validatedCopy, nil
}
// NOTE: can be used with: return ygot.EmitJSON(d.model, getYgotEmitJSONConfig())
// Kept in case we do not want to use ygot.Marshal7951
//func getYgotEmitJSONConfig() *ygot.EmitJSONConfig {
// return &ygot.EmitJSONConfig{
// Format: ygot.RFC7951,
// Indent: "",
// SkipValidation: true,
// RFC7951Config: &ygot.RFC7951JSONConfig{
// AppendModuleName: true,
// }}
//}
func getYgotMarshal7951Config() *ygot.RFC7951JSONConfig {
return &ygot.RFC7951JSONConfig{
AppendModuleName: true,
}
}