-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
scopes.go
210 lines (187 loc) · 5.25 KB
/
scopes.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
package dhcp
import (
"context"
"encoding/json"
"fmt"
"net"
"net/netip"
"strings"
"time"
"beryju.io/gravity/pkg/roles"
"beryju.io/gravity/pkg/roles/dhcp/types"
"github.com/insomniacslk/dhcp/dhcpv4"
"go.etcd.io/etcd/api/v3/mvccpb"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/zap"
)
type ScopeDNS struct {
Zone string `json:"zone"`
Search []string `json:"search"`
AddZoneInHostname bool `json:"addZoneInHostname"`
}
type Scope struct {
ipam IPAM
inst roles.Instance
DNS *ScopeDNS `json:"dns"`
IPAM map[string]string `json:"ipam"`
role *Role
log *zap.Logger
cidr netip.Prefix
Name string `json:"-"`
etcdKey string
SubnetCIDR string `json:"subnetCidr"`
Options []*types.DHCPOption `json:"options"`
TTL int64 `json:"ttl"`
Default bool `json:"default"`
Hook string `json:"hook"`
}
func (r *Role) NewScope(name string) *Scope {
return &Scope{
Name: name,
inst: r.i,
role: r,
TTL: int64((7 * 24 * time.Hour).Seconds()),
log: r.log.With(zap.String("scope", name)),
DNS: &ScopeDNS{},
IPAM: make(map[string]string),
}
}
func (r *Role) scopeFromKV(raw *mvccpb.KeyValue) (*Scope, error) {
prefix := r.i.KV().Key(types.KeyRole, types.KeyScopes).Prefix(true).String()
name := strings.TrimPrefix(string(raw.Key), prefix)
s := r.NewScope(name)
err := json.Unmarshal(raw.Value, &s)
if err != nil {
return nil, err
}
cidr, err := netip.ParsePrefix(s.SubnetCIDR)
if err != nil {
return nil, err
}
s.cidr = cidr
s.etcdKey = string(raw.Key)
previous := r.scopes[s.Name]
ipamInst, err := s.ipamType(previous)
if err != nil {
return nil, fmt.Errorf("failed to create ipam: %w", err)
}
s.ipam = ipamInst
return s, nil
}
func (s *Scope) ipamType(previous *Scope) (IPAM, error) {
if previous != nil && s.IPAM["type"] == previous.IPAM["type"] {
err := previous.ipam.UpdateConfig(s)
return previous.ipam, err
}
switch s.IPAM["type"] {
case InternalIPAMType:
fallthrough
default:
return NewInternalIPAM(s.role, s)
}
}
func (r *Role) findScopeForRequest(req *Request4) *Scope {
var match *Scope
longestBits := 0
r.scopesM.RLock()
defer r.scopesM.RUnlock()
// To prioritise requests from a DHCP relay being matched correctly, give their subnet
// match a 1 bit more priority
const dhcpRelayBias = 1
const clientIPBias = 2
for _, scope := range r.scopes {
// Check based on Client IP Address (highest priority)
clientIPMatchBits := scope.match(req.ClientIPAddr)
if clientIPMatchBits > -1 && clientIPMatchBits+clientIPBias > longestBits {
req.log.Debug("selected scope based on client IP", zap.String("scope", scope.Name))
match = scope
longestBits = clientIPMatchBits + clientIPBias
}
// Check based on gateway IP (next highest priority)
gatewayMatchBits := scope.match(req.GatewayIPAddr)
if gatewayMatchBits > -1 && gatewayMatchBits+dhcpRelayBias > longestBits {
req.log.Debug("selected scope based on cidr match (gateway IP)", zap.String("scope", scope.Name))
match = scope
longestBits = gatewayMatchBits + dhcpRelayBias
}
// Handle local broadcast, check with the instance's listening IP
// Only consider local scopes if we don't have a match already
localMatchBits := scope.match(net.ParseIP(req.LocalIP()))
if localMatchBits > -1 && localMatchBits > longestBits {
req.log.Debug("selected scope based on cidr match (instance/interface IP)", zap.String("scope", scope.Name))
match = scope
longestBits = localMatchBits
}
// Fallback to default scope if we don't already have a match
if match == nil && scope.Default {
req.log.Debug("selected scope based on default flag", zap.String("scope", scope.Name))
match = scope
}
}
if match != nil {
req.log.Debug("final scope selection", zap.String("scope", match.Name))
}
return match
}
func (s *Scope) match(peer net.IP) int {
ip, err := netip.ParseAddr(peer.String())
if err != nil {
s.log.Warn("failed to parse client ip", zap.Error(err))
return -1
}
if s.cidr.Contains(ip) {
return s.cidr.Bits()
}
return -1
}
func (s *Scope) leaseFor(req *Request4) *Lease {
ident := s.role.DeviceIdentifier(req.DHCPv4)
lease := s.role.NewLease(ident)
lease.Hostname = req.HostName()
lease.scope = s
lease.ScopeKey = s.Name
lease.setLeaseIP(req)
req.log.Info("creating new DHCP lease", zap.String("ip", lease.Address), zap.String("identifier", ident))
return lease
}
func (s *Scope) Put(ctx context.Context, expiry int64, opts ...clientv3.OpOption) error {
raw, err := json.Marshal(&s)
if err != nil {
return err
}
if expiry > 0 {
exp, err := s.inst.KV().Lease.Grant(ctx, expiry)
if err != nil {
return err
}
opts = append(opts, clientv3.WithLease(exp.ID))
}
leaseKey := s.inst.KV().Key(
types.KeyRole,
types.KeyScopes,
s.Name,
)
_, err = s.inst.KV().Put(
ctx,
leaseKey.String(),
string(raw),
opts...,
)
if err != nil {
return err
}
return nil
}
func (s *Scope) executeHook(method string, args ...interface{}) {
s.role.i.ExecuteHook(roles.HookOptions{
Source: s.Hook,
Method: method,
Env: map[string]interface{}{
"dhcp": map[string]interface{}{
"Opt": func(code uint8, data []byte) dhcpv4.Option {
return dhcpv4.OptGeneric(dhcpv4.GenericOptionCode(code), data)
},
},
},
}, args...)
}