This repository has been archived by the owner on Aug 3, 2020. It is now read-only.
forked from ligato/vpp-agent
/
spec.go
269 lines (230 loc) · 6.78 KB
/
spec.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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 of the 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 specific language governing permissions and
// limitations under the License.
package models
import (
"fmt"
"net"
"os"
"regexp"
"strings"
"text/template"
"github.com/gogo/protobuf/proto"
api "github.com/ligato/vpp-agent/api/genericmanager"
)
var (
validModule = regexp.MustCompile(`^[-a-z0-9_]+(?:\.[-a-z0-9_]+)?$`)
validType = regexp.MustCompile(`^[-a-z0-9_]+$`)
)
// Spec defines model specification used for registering model.
type Spec api.Model
type registeredModel struct {
Spec
protoName string
keyPrefix string
modelPath string
modelOptions
}
// NameFunc represents function which can name model instance.
type NameFunc func(obj interface{}) (string, error)
type modelOptions struct {
nameTemplate string
nameFunc NameFunc
}
// ModelOption defines function type which sets model options.
type ModelOption func(*modelOptions)
// WithNameTemplate returns option for models which sets function
// for generating name of instances using custom template.
func WithNameTemplate(t string) ModelOption {
return func(opts *modelOptions) {
opts.nameFunc = NameTemplate(t)
opts.nameTemplate = t
}
}
// ProtoName returns proto message name registered with the model.
func (m registeredModel) ProtoName() string {
return m.protoName
}
// Path returns path for the model.
func (m registeredModel) Path() string {
return m.modelPath
}
// KeyPrefix returns key prefix for the model.
func (m registeredModel) KeyPrefix() string {
return m.keyPrefix
}
// ParseKey parses the given key and returns item name
// or returns empty name and valid as false if the key is not valid.
func (m registeredModel) ParseKey(key string) (name string, valid bool) {
name = strings.TrimPrefix(key, m.keyPrefix)
if name == key || (name == "" && m.nameFunc != nil) {
name = strings.TrimPrefix(key, m.modelPath)
}
// key had the prefix and also either
// non-empty name or no name template
if name != key && (name != "" || m.nameFunc == nil) {
// TODO: validate name?
return name, true
}
return "", false
}
// IsKeyValid returns true if given key is valid for this model.
func (m registeredModel) IsKeyValid(key string) bool {
_, valid := m.ParseKey(key)
return valid
}
// StripKeyPrefix returns key with prefix stripped.
func (m registeredModel) StripKeyPrefix(key string) string {
if name, valid := m.ParseKey(key); valid {
return name
}
return key
}
func (m registeredModel) name(x proto.Message) (string, error) {
if m.nameFunc == nil {
return "", nil
}
return m.nameFunc(x)
}
var (
registeredModels = make(map[string]*registeredModel)
modelPaths = make(map[string]string)
debugRegister = strings.Contains(os.Getenv("DEBUG_MODELS"), "register")
)
// RegisteredModels returns all registered modules.
func RegisteredModels() (models []*api.ModelInfo) {
for _, s := range registeredModels {
models = append(models, &api.ModelInfo{
Model: &api.Model{
Module: s.Module,
Type: s.Type,
Version: s.Version,
},
Info: map[string]string{
"nameTemplate": s.nameTemplate,
"protoName": s.protoName,
"modelPath": s.modelPath,
"keyPrefix": s.keyPrefix,
},
})
}
return
}
// Register registers the protobuf message with given model specification.
func Register(pb proto.Message, spec Spec, opts ...ModelOption) *registeredModel {
model := ®isteredModel{
Spec: spec,
protoName: proto.MessageName(pb),
}
// Check proto message name
if model.protoName == "" {
panic(fmt.Sprintf("empty proto message name for type: %T\n\n\tPlease ensure your .proto file contains: 'option (gogoproto.messagename_all) = true'", pb))
}
// Check duplicate registration
if _, ok := registeredModels[model.protoName]; ok {
panic(fmt.Sprintf("proto message %q already registered", model.protoName))
}
// Validate model spec
if !validModule.MatchString(spec.Module) {
panic(fmt.Sprintf("module for model %s is invalid", model.protoName))
}
if !validType.MatchString(spec.Type) {
panic(fmt.Sprintf("model type for %s is invalid", model.protoName))
}
if !strings.HasPrefix(spec.Version, "v") {
panic(fmt.Sprintf("model version for %s is invalid", model.protoName))
}
// Generate keys & paths
model.modelPath = buildModelPath(spec.Version, spec.Module, spec.Type)
if pn, ok := modelPaths[model.modelPath]; ok {
panic(fmt.Sprintf("path prefix %q already used by: %s", model.modelPath, pn))
}
modulePath := strings.Replace(spec.Module, ".", "/", -1)
model.keyPrefix = fmt.Sprintf("config/%s/%s/%s/", modulePath, spec.Version, spec.Type)
// Use GetName as fallback for generating name
if _, ok := pb.(named); ok {
model.nameFunc = func(obj interface{}) (s string, e error) {
return obj.(named).GetName(), nil
}
}
// Apply custom options
for _, opt := range opts {
opt(&model.modelOptions)
}
if model.nameFunc == nil {
model.keyPrefix = strings.TrimSuffix(model.keyPrefix, "/")
}
registeredModels[model.protoName] = model
modelPaths[model.modelPath] = model.protoName
if debugRegister {
fmt.Printf("- registered model: %+v\t%q\n", model, model.modelPath)
}
return model
}
func buildModelPath(version, module, typ string) string {
return fmt.Sprintf("%s.%s.%s", module, version, typ)
}
type named interface {
GetName() string
}
func NameTemplate(t string) NameFunc {
tmpl := template.Must(
template.New("name").Funcs(funcMap).Option("missingkey=error").Parse(t),
)
return func(obj interface{}) (string, error) {
var s strings.Builder
if err := tmpl.Execute(&s, obj); err != nil {
return "", err
}
return s.String(), nil
}
}
var funcMap = template.FuncMap{
"ip": func(s string) string {
ip := net.ParseIP(s)
if ip == nil {
return "<invalid>"
}
return ip.String()
},
"protoip": func(s string) string {
ip := net.ParseIP(s)
if ip == nil {
return "<invalid>"
}
if ip.To4() == nil {
return "IPv6"
}
return "IPv4"
},
"ipnet": func(s string) map[string]interface{} {
if strings.HasPrefix(s, "alloc:") {
// reference to IP address allocated via netalloc
return nil
}
_, ipNet, err := net.ParseCIDR(s)
if err != nil {
return map[string]interface{}{
"IP": "<invalid>",
"MaskSize": 0,
"AllocRef": "",
}
}
maskSize, _ := ipNet.Mask.Size()
return map[string]interface{}{
"IP": ipNet.IP.String(),
"MaskSize": maskSize,
"AllocRef": "",
}
},
}