forked from networkservicemesh/examples
-
Notifications
You must be signed in to change notification settings - Fork 5
/
helper.go
98 lines (88 loc) · 2.27 KB
/
helper.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
package ipprovider
import (
"bytes"
"fmt"
"net"
"github.com/pkg/errors"
)
type validationErrors []error
func (e validationErrors) Error() string {
b := bytes.NewBufferString("")
for _, err := range e {
_, _ = fmt.Fprintf(b, "\t%s", err)
}
return b.String()
}
func (m *Identifier) Validate() error {
var errs validationErrors
if m.GetConnectivityDomain() == "" {
errs = append(errs, errors.Errorf("connectivity domain is a mandatory parameter %v", m))
}
if m.GetFqdn() == "" {
errs = append(errs, errors.Errorf("fqdn is a mandatory parameter %v", m))
}
if m.GetName() == "" {
errs = append(errs, errors.Errorf("name is a mandatory parameter %v", m))
}
if len(errs) != 0 {
return errs
}
return nil
}
func (m *SubnetRequest) Validate() error {
var errs validationErrors
err := m.GetIdentifier().Validate()
if err != nil {
errs = append(errs, err)
}
switch m.GetAddrFamily().GetFamily() {
case IpFamily_IPV4:
if m.GetPrefixLen() > 32 || m.GetPrefixLen() < 2 {
errs = append(errs, errors.New("invalid prefix length for IPv4 - should be positive integer >=2 and <=32"))
}
case IpFamily_IPV6:
if m.GetPrefixLen() > 128 || m.GetPrefixLen() < 2 {
errs = append(errs, errors.New("invalid prefix length for IPv4 - should be positive integer >=2 and <=32"))
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func (m *Subnet) Validate() error {
var errs validationErrors
err := m.GetIdentifier().Validate()
if err != nil {
errs = append(errs, err)
}
err = m.GetPrefix().Validate()
if err != nil {
errs = append(errs, err)
}
if len(errs) > 0 {
return errs
}
return nil
}
func (m *IpPrefix) Validate() error {
ip, _, err := net.ParseCIDR(m.GetSubnet())
if err != nil {
return errors.Errorf("subnetcalculator is not valid: %v", err)
}
isIpV4 := ip.To4() != nil
if m.GetAddrFamily().GetFamily() == IpFamily_IPV6 && isIpV4 {
return errors.Errorf("IPv4 subnetcalculator given for IPv6 address family: %v", m)
}
if m.GetAddrFamily().GetFamily() == IpFamily_IPV4 && !isIpV4 {
return errors.Errorf("IPv6 subnetcalculator given for IPv4 address family: %v", m)
}
return nil
}
func (m *IpPrefix) ToIpNet() *net.IPNet {
_, ipNet, _ := net.ParseCIDR(m.GetSubnet())
return ipNet
}
func (m *IpFamily) GetFamilyString() string {
return m.Family.String()
}