/
validator.go
75 lines (64 loc) · 2.13 KB
/
validator.go
1
2
3
4
5
6
7
8
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
/*
* Copyright (C) 2018 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy ofthe License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specificlanguage governing permissions and
* limitations under the License.
*
*/
package topology
import (
"errors"
"github.com/skydive-project/skydive/graffiti/graph"
"github.com/skydive-project/skydive/statics"
"github.com/xeipuuv/gojsonschema"
)
// ErrInvalidSchema is return when a JSON schema is invalid
var ErrInvalidSchema = errors.New("Invalid schema")
// SchemaValidator validates graph nodes and edges using a JSON schema
type SchemaValidator struct {
nodeSchema gojsonschema.JSONLoader
edgeSchema gojsonschema.JSONLoader
}
func (v *SchemaValidator) validate(obj interface{}, schema gojsonschema.JSONLoader) error {
loader := gojsonschema.NewGoLoader(obj)
result, err := gojsonschema.Validate(schema, loader)
if err != nil {
return err
} else if !result.Valid() {
return ErrInvalidSchema
}
return nil
}
// ValidateNode valides a graph node
func (v *SchemaValidator) ValidateNode(node *graph.Node) error {
return v.validate(node, v.nodeSchema)
}
// ValidateEdge valides a graph edge
func (v *SchemaValidator) ValidateEdge(edge *graph.Edge) error {
return v.validate(edge, v.edgeSchema)
}
// NewSchemaValidator returns a new JSON schema validator for
// graph nodes and edges. based on JSON schema bundled with go-bindata
func NewSchemaValidator() (*SchemaValidator, error) {
nodeSchema, err := statics.Asset("statics/schemas/node.schema")
if err != nil {
return nil, err
}
edgeSchema, err := statics.Asset("statics/schemas/edge.schema")
if err != nil {
return nil, err
}
return &SchemaValidator{
nodeSchema: gojsonschema.NewBytesLoader(nodeSchema),
edgeSchema: gojsonschema.NewBytesLoader(edgeSchema),
}, nil
}