Newer
Older
package sdk
import (
"fmt"
"strconv"
"time"
mnepb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/networkelement"
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"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,
}, nil
}
// 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...)
}
// GetNode gets the node for the given path.
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
}
notifications := make([]*gpb.Notification, len(nodes))
for i, node := range nodes {
generatedNotifictaions, err := genGnmiNotification(path, node.Data)
if err != nil {
return nil, status.Errorf(codes.Aborted, "%v", err)
}
notifications[i] = generatedNotifictaions
}
return notifications, nil
}
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(filterReadOnly bool) ([]byte, error) {
modelCopy, err := createValidatedCopy(d.model)
if err != nil {
return nil, err
}
if filterReadOnly {
if err := ygot.PruneConfigFalse(d.schema.RootSchema(), modelCopy); err != nil {
return nil, err
}
}
return ygot.Marshal7951(modelCopy, 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 {
return nil, err
}
if err := d.generatedUnmarshalFn(modified, modifiedAsValidatedCopy, opts...); err != nil {
return nil, err
}
return ygot.Diff(originalAsValidatedCopy, modifiedAsValidatedCopy)
}
func (d *DeviceModel) ValidateChange(operation mnepb.ApiOperation, path *gpb.Path, value []byte) ([]byte, error) {
modelCopy, err := createValidatedCopy(d.model)
if err != nil {
return nil, err
}
switch operation {
case mnepb.ApiOperation_API_OPERATION_UPDATE, mnepb.ApiOperation_API_OPERATION_REPLACE:
createdNode, entry, err := ytypes.GetOrCreateNode(d.schema.RootSchema(), modelCopy, path)
if err != nil {
return nil, err
}
validatedCreatedNode, ok := createdNode.(ygot.ValidatedGoStruct)
if !ok {
return nil, &customerrs.InvalidTypeAssertionError{
Value: createdNode,
Type: (*ygot.ValidatedGoStruct)(nil),
}
}
if entry.IsDir() {
opts := []ytypes.UnmarshalOpt{
// NOTE: I think we should not ignore extra fields if we want
// to validate a specific change. The input for a valid change
// should be correct to be valid.
//
//&ytypes.IgnoreExtraFields{}
}
if err := d.generatedUnmarshalFn(value, validatedCreatedNode, 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(), validatedCreatedNode, path, typedValue, opts...); err != nil {
return nil, err
}
}
case mnepb.ApiOperation_API_OPERATION_DELETE:
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
337
338
339
340
341
342
343
344
345
346
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(""))
}
func (d *DeviceModel) PruneConfigFalse(value []byte) ([]byte, error) {
validatedCopy, err := createValidatedCopy(d.schema.Root)
if err != nil {
return nil, err
}
opts := []ytypes.UnmarshalOpt{&ytypes.IgnoreExtraFields{}}
if err := d.generatedUnmarshalFn(value, validatedCopy, opts...); err != nil {
return nil, err
}
if err := ygot.PruneConfigFalse(d.schema.RootSchema(), validatedCopy); err != nil {
return nil, err
}
return ygot.Marshal7951(validatedCopy, getYgotMarshal7951Config(), ygot.JSONIndent(""))
}
// 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,
}
}