-
Notifications
You must be signed in to change notification settings - Fork 286
/
param_types.go
509 lines (457 loc) · 12.6 KB
/
param_types.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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright (c) 2016-2019 Tigera, Inc. All rights reserved.
//
// 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 config
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"os/exec"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"k8s.io/apimachinery/pkg/util/validation"
"github.com/kardianos/osext"
log "github.com/sirupsen/logrus"
cnet "github.com/projectcalico/libcalico-go/lib/net"
"github.com/projectcalico/libcalico-go/lib/numorstring"
)
const (
MinIptablesMarkBits = 2
)
type Metadata struct {
Name string
Default interface{}
ZeroValue interface{}
NonZero bool
DieOnParseFailure bool
Local bool
}
func (m *Metadata) GetMetadata() *Metadata {
return m
}
func (m *Metadata) parseFailed(raw, msg string) error {
return fmt.Errorf("Failed to parse config parameter %v; value %#v: %v", m.Name, raw, msg)
}
func (m *Metadata) setDefault(config *Config) {
log.Debugf("Defaulting: %v to %v", m.Name, m.Default)
field := reflect.ValueOf(config).Elem().FieldByName(m.Name)
value := reflect.ValueOf(m.Default)
field.Set(value)
}
type BoolParam struct {
Metadata
}
func (p *BoolParam) Parse(raw string) (interface{}, error) {
switch strings.ToLower(raw) {
case "true", "1", "yes", "y", "t":
return true, nil
case "false", "0", "no", "n", "f":
return false, nil
}
return nil, p.parseFailed(raw, "invalid boolean")
}
type IntParam struct {
Metadata
Min int
Max int
}
func (p *IntParam) Parse(raw string) (interface{}, error) {
value, err := strconv.ParseInt(raw, 0, 64)
if err != nil {
err = p.parseFailed(raw, "invalid int")
return nil, err
}
result := int(value)
if result < p.Min {
err = p.parseFailed(raw,
fmt.Sprintf("value must be at least %v", p.Min))
} else if result > p.Max {
err = p.parseFailed(raw,
fmt.Sprintf("value must be at most %v", p.Max))
}
return result, err
}
type Int32Param struct {
Metadata
}
func (p *Int32Param) Parse(raw string) (interface{}, error) {
value, err := strconv.ParseInt(raw, 0, 32)
if err != nil {
err = p.parseFailed(raw, "invalid 32-bit int")
return nil, err
}
result := int32(value)
return result, err
}
type FloatParam struct {
Metadata
}
func (p *FloatParam) Parse(raw string) (result interface{}, err error) {
result, err = strconv.ParseFloat(raw, 64)
if err != nil {
err = p.parseFailed(raw, "invalid float")
return
}
return
}
type SecondsParam struct {
Metadata
}
func (p *SecondsParam) Parse(raw string) (result interface{}, err error) {
seconds, err := strconv.ParseFloat(raw, 64)
if err != nil {
err = p.parseFailed(raw, "invalid float")
return
}
result = time.Duration(seconds * float64(time.Second))
return
}
type MillisParam struct {
Metadata
}
func (p *MillisParam) Parse(raw string) (result interface{}, err error) {
millis, err := strconv.ParseFloat(raw, 64)
if err != nil {
err = p.parseFailed(raw, "invalid float")
return
}
result = time.Duration(millis * float64(time.Millisecond))
return
}
type RegexpParam struct {
Metadata
Regexp *regexp.Regexp
Msg string
}
func (p *RegexpParam) Parse(raw string) (result interface{}, err error) {
if !p.Regexp.MatchString(raw) {
err = p.parseFailed(raw, p.Msg)
} else {
result = raw
}
return
}
// RegexpPatternParam differs from RegexpParam (above) in that it validates
// string values that are (themselves) regular expressions.
type RegexpPatternParam struct {
Metadata
}
// Parse validates whether the given raw string contains a valid regexp pattern.
func (p *RegexpPatternParam) Parse(raw string) (interface{}, error) {
var result *regexp.Regexp
result, compileErr := regexp.Compile(raw)
if compileErr != nil {
return nil, p.parseFailed(raw, "invalid regexp")
}
return result, nil
}
// RegexpPatternListParam differs from RegexpParam (above) in that it validates
// string values that are (themselves) regular expressions.
type RegexpPatternListParam struct {
Metadata
RegexpElemRegexp *regexp.Regexp
NonRegexpElemRegexp *regexp.Regexp
Delimiter string
Msg string
}
// Parse validates whether the given raw string contains a list of valid values.
// Validation is dictated by two regexp patterns: one for valid regular expression
// values, another for non-regular expressions.
func (p *RegexpPatternListParam) Parse(raw string) (interface{}, error) {
var result []*regexp.Regexp
// Split into individual elements, then validate each one and compile to regexp
tokens := strings.Split(raw, p.Delimiter)
for _, t := range tokens {
if p.RegexpElemRegexp.Match([]byte(t)) {
// Need to remove the start and end symbols that wrap the actual regexp
// Note: There's a coupling here with the assumed pattern in RegexpElemRegexp
// i.e. that each value is wrapped by a single char symbol on either side
regexpValue := t[1 : len(t)-1]
compiledRegexp, compileErr := regexp.Compile(regexpValue)
if compileErr != nil {
return nil, p.parseFailed(raw, p.Msg)
}
result = append(result, compiledRegexp)
} else if p.NonRegexpElemRegexp.Match([]byte(t)) {
compiledRegexp, compileErr := regexp.Compile("^" + regexp.QuoteMeta(t) + "$")
if compileErr != nil {
return nil, p.parseFailed(raw, p.Msg)
}
result = append(result, compiledRegexp)
} else {
return nil, p.parseFailed(raw, p.Msg)
}
}
return result, nil
}
type FileParam struct {
Metadata
MustExist bool
Executable bool
}
func (p *FileParam) Parse(raw string) (interface{}, error) {
if p.Executable {
// Special case: for executable files, we search our directory
// and the system path.
logCxt := log.WithField("name", raw)
var path string
if myDir, err := osext.ExecutableFolder(); err == nil {
logCxt.WithField("myDir", myDir).Info(
"Looking for executable in my directory")
path = myDir + string(os.PathSeparator) + raw
stat, err := os.Stat(path)
if err == nil {
if m := stat.Mode(); !m.IsDir() && m&0111 > 0 {
return path, nil
}
} else {
logCxt.WithField("myDir", myDir).Info(
"No executable in my directory")
path = ""
}
} else {
logCxt.WithError(err).Warn("Failed to get my dir")
}
if path == "" {
logCxt.Info("Looking for executable on path")
var err error
path, err = exec.LookPath(raw)
if err != nil {
logCxt.WithError(err).Warn("Path lookup failed")
path = ""
}
}
if path == "" && p.MustExist {
log.Error("Executable missing")
return nil, p.parseFailed(raw, "missing file")
}
log.WithField("path", path).Info("Executable path")
return path, nil
} else if p.MustExist && raw != "" {
log.WithField("path", raw).Info("Looking for required file")
_, err := os.Stat(raw)
if err != nil {
log.Errorf("Failed to access %v: %v", raw, err)
return nil, p.parseFailed(raw, "failed to access file")
}
}
return raw, nil
}
type Ipv4Param struct {
Metadata
}
func (p *Ipv4Param) Parse(raw string) (result interface{}, err error) {
res := net.ParseIP(raw)
if res == nil {
err = p.parseFailed(raw, "invalid IP")
}
result = res
return
}
type PortListParam struct {
Metadata
}
func (p *PortListParam) Parse(raw string) (interface{}, error) {
var result []ProtoPort
for _, portStr := range strings.Split(raw, ",") {
portStr = strings.Trim(portStr, " ")
if portStr == "" {
continue
}
parts := strings.Split(portStr, ":")
if len(parts) > 2 {
return nil, p.parseFailed(raw,
"ports should be <protocol>:<number> or <number>")
}
protocolStr := "tcp"
if len(parts) > 1 {
protocolStr = strings.ToLower(parts[0])
portStr = parts[1]
}
if protocolStr != "tcp" && protocolStr != "udp" {
return nil, p.parseFailed(raw, "unknown protocol: "+protocolStr)
}
port, err := strconv.Atoi(portStr)
if err != nil {
err = p.parseFailed(raw, "ports should be integers")
return nil, err
}
if port < 0 || port > 65535 {
err = p.parseFailed(raw, "ports must be in range 0-65535")
return nil, err
}
result = append(result, ProtoPort{
Protocol: protocolStr,
Port: uint16(port),
})
}
return result, nil
}
type PortRangeParam struct {
Metadata
}
func (p *PortRangeParam) Parse(raw string) (interface{}, error) {
portRange, err := numorstring.PortFromString(raw)
if err != nil {
return nil, p.parseFailed(raw, fmt.Sprintf("%s is not a valid port range", raw))
}
if len(portRange.PortName) > 0 {
return nil, p.parseFailed(raw, fmt.Sprintf("%s has port name set", raw))
}
return portRange, nil
}
type PortRangeListParam struct {
Metadata
}
func (p *PortRangeListParam) Parse(raw string) (interface{}, error) {
var result []numorstring.Port
for _, rangeStr := range strings.Split(raw, ",") {
portRange, err := numorstring.PortFromString(rangeStr)
if err != nil {
return nil, p.parseFailed(raw, fmt.Sprintf("%s is not a valid port range", rangeStr))
}
if len(portRange.PortName) > 0 {
return nil, p.parseFailed(raw, fmt.Sprintf("%s has port name set", rangeStr))
}
result = append(result, portRange)
}
return result, nil
}
type EndpointListParam struct {
Metadata
}
func (p *EndpointListParam) Parse(raw string) (result interface{}, err error) {
value := strings.Split(raw, ",")
scheme := ""
resultSlice := []string{}
for _, endpoint := range value {
endpoint = strings.Trim(endpoint, " ")
if len(endpoint) == 0 {
continue
}
var u *url.URL
u, err = url.Parse(endpoint)
if err != nil {
err = p.parseFailed(raw,
fmt.Sprintf("%v is not a valid URL", endpoint))
return
}
if scheme != "" && u.Scheme != scheme {
err = p.parseFailed(raw,
"all endpoints must have the same scheme")
return
}
if u.Path == "" {
u.Path = "/"
}
if u.Opaque != "" || u.User != nil || u.Path != "/" ||
u.RawPath != "" || u.RawQuery != "" ||
u.Fragment != "" {
log.WithField("url", fmt.Sprintf("%#v", u)).Error(
"Unsupported URL part")
err = p.parseFailed(raw,
"endpoint contained unsupported URL part; "+
"expected http(s)://hostname:port only.")
return
}
resultSlice = append(resultSlice, u.String())
}
result = resultSlice
return
}
type MarkBitmaskParam struct {
Metadata
}
func (p *MarkBitmaskParam) Parse(raw string) (interface{}, error) {
value, err := strconv.ParseUint(raw, 0, 32)
if err != nil {
log.Warningf("Failed to parse %#v as an int: %v", raw, err)
err = p.parseFailed(raw, "invalid mark: should be 32-bit int")
return nil, err
}
result := uint32(value)
bitCount := uint32(0)
for i := uint(0); i < 32; i++ {
bit := (result >> i) & 1
bitCount += bit
}
if bitCount < MinIptablesMarkBits {
err = p.parseFailed(raw,
fmt.Sprintf("invalid mark: needs to have %v bits set",
MinIptablesMarkBits))
}
return result, err
}
type OneofListParam struct {
Metadata
lowerCaseOptionsToCanonical map[string]string
}
func (p *OneofListParam) Parse(raw string) (result interface{}, err error) {
result, ok := p.lowerCaseOptionsToCanonical[strings.ToLower(raw)]
if !ok {
err = p.parseFailed(raw, "unknown option")
}
return
}
type CIDRListParam struct {
Metadata
}
func (c *CIDRListParam) Parse(raw string) (result interface{}, err error) {
log.WithField("CIDRs raw", raw).Info("CIDRList")
values := strings.Split(raw, ",")
resultSlice := []string{}
for _, in := range values {
val := strings.Trim(in, " ")
if len(val) == 0 {
continue
}
ip, net, e := cnet.ParseCIDROrIP(val)
if e != nil {
err = c.parseFailed(in, "invalid CIDR or IP "+val)
return
}
if ip.Version() != 4 {
err = c.parseFailed(in, "invalid CIDR or IP (not v4)")
return
}
resultSlice = append(resultSlice, net.String())
}
return resultSlice, nil
}
type RegionParam struct {
Metadata
}
const regionNamespacePrefix = "openstack-region-"
const maxRegionLength int = validation.DNS1123LabelMaxLength - len(regionNamespacePrefix)
func (r *RegionParam) Parse(raw string) (result interface{}, err error) {
log.WithField("raw", raw).Info("Region")
if len(raw) > maxRegionLength {
err = fmt.Errorf("The value of OpenstackRegion must be %v chars or fewer", maxRegionLength)
return
}
errs := validation.IsDNS1123Label(raw)
if len(errs) != 0 {
msg := "The value of OpenstackRegion must be a valid DNS label"
for _, err := range errs {
msg = msg + "; " + err
}
err = errors.New(msg)
return
}
return raw, nil
}