forked from metallb/metallb
/
layer2_controller.go
242 lines (217 loc) · 6.91 KB
/
layer2_controller.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
// Copyright 2017 Google 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 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 main
import (
"bytes"
"crypto/sha256"
"net"
"sort"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"go.universe.tf/metallb/internal/config"
"go.universe.tf/metallb/internal/k8s/epslices"
k8snodes "go.universe.tf/metallb/internal/k8s/nodes"
"go.universe.tf/metallb/internal/layer2"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
type layer2Controller struct {
announcer *layer2.Announce
myNode string
sList SpeakerList
}
func (c *layer2Controller) SetConfig(log.Logger, *config.Config) error {
return nil
}
// usableNodes returns all nodes that have at least one fully ready
// endpoint on them.
// The speakers parameter is a map containing all the nodes with active speakers.
// If the speakers map is nil, it is ignored.
func usableNodes(eps epslices.EpsOrSlices, speakers map[string]bool) []string {
usable := map[string]bool{}
switch eps.Type {
case epslices.Eps:
for _, subset := range eps.EpVal.Subsets {
for _, ep := range subset.Addresses {
if ep.NodeName == nil {
continue
}
if speakers != nil {
if hasSpeaker := speakers[*ep.NodeName]; !hasSpeaker {
continue
}
}
if _, ok := usable[*ep.NodeName]; !ok {
usable[*ep.NodeName] = true
}
}
}
case epslices.Slices:
for _, slice := range eps.SlicesVal {
for _, ep := range slice.Endpoints {
if !epslices.IsConditionServing(ep.Conditions) {
continue
}
if ep.NodeName == nil {
continue
}
nodeName := *ep.NodeName
if speakers != nil {
if hasSpeaker := speakers[nodeName]; !hasSpeaker {
continue
}
}
if _, ok := usable[nodeName]; !ok {
usable[nodeName] = true
}
}
}
}
var ret []string
for node, ok := range usable {
if ok {
ret = append(ret, node)
}
}
return ret
}
func (c *layer2Controller) ShouldAnnounce(l log.Logger, name string, toAnnounce []net.IP, pool *config.Pool, svc *v1.Service, eps epslices.EpsOrSlices, nodes map[string]*v1.Node) string {
if !activeEndpointExists(eps) { // no active endpoints, just return
level.Debug(l).Log("event", "shouldannounce", "protocol", "l2", "message", "failed no active endpoints", "service", name)
return "notOwner"
}
if !poolMatchesNodeL2(pool, c.myNode) {
level.Debug(l).Log("event", "skipping should announce l2", "service", name, "reason", "pool not matching my node")
return "notOwner"
}
// we select the nodes with at least one matching l2 advertisement
forPool := speakersForPool(c.sList.UsableSpeakers(), pool, nodes)
var availableNodes []string
if svc.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyTypeLocal {
availableNodes = usableNodes(eps, forPool)
} else {
availableNodes = nodesWithActiveSpeakers(forPool)
}
if len(availableNodes) == 0 {
level.Debug(l).Log("event", "skipping should announce l2", "service", name, "reason", "no available nodes")
return "notOwner"
}
level.Debug(l).Log("event", "shouldannounce", "protocol", "l2", "nodes", availableNodes, "service", name)
// Using the first IP should work for both single and dual stack.
ipString := toAnnounce[0].String()
// Sort the slice by the hash of node + load balancer ips. This
// produces an ordering of ready nodes that is unique to all the services
// with the same ip.
sort.Slice(availableNodes, func(i, j int) bool {
hi := sha256.Sum256([]byte(availableNodes[i] + "#" + ipString))
hj := sha256.Sum256([]byte(availableNodes[j] + "#" + ipString))
return bytes.Compare(hi[:], hj[:]) < 0
})
// Are we first in the list? If so, we win and should announce.
if len(availableNodes) > 0 && availableNodes[0] == c.myNode {
return ""
}
// Either not eligible, or lost the election entirely.
return "notOwner"
}
func (c *layer2Controller) SetBalancer(l log.Logger, name string, lbIPs []net.IP, pool *config.Pool, client service, svc *v1.Service) error {
ifs := c.announcer.GetInterfaces()
for _, lbIP := range lbIPs {
ipAdv := ipAdvertisementFor(lbIP, c.myNode, pool.L2Advertisements)
if !ipAdv.MatchInterfaces(ifs...) {
level.Warn(l).Log("op", "SetBalancer", "protocol", "layer2", "service", name, "IPAdvertisement", ipAdv,
"localIfs", ifs, "msg", "the specified interfaces used to announce LB IP don't exist")
client.Errorf(svc, "announceFailed", "the interfaces specified by LB IP %q doesn't exist in assigned node %q with protocol %q", lbIP.String(), c.myNode, config.Layer2)
continue
}
c.announcer.SetBalancer(name, ipAdv)
}
return nil
}
func (c *layer2Controller) DeleteBalancer(l log.Logger, name, reason string) error {
if !c.announcer.AnnounceName(name) {
return nil
}
c.announcer.DeleteBalancer(name)
return nil
}
func (c *layer2Controller) SetNode(l log.Logger, n *v1.Node) error {
if c.myNode != n.Name {
return nil
}
c.sList.Rejoin()
return nil
}
func ipAdvertisementFor(ip net.IP, localNode string, l2Advertisements []*config.L2Advertisement) layer2.IPAdvertisement {
ifs := sets.Set[string]{}
for _, l2 := range l2Advertisements {
if matchNode := l2.Nodes[localNode]; !matchNode {
continue
}
if l2.AllInterfaces {
return layer2.NewIPAdvertisement(ip, true, sets.Set[string]{})
}
ifs = ifs.Insert(l2.Interfaces...)
}
return layer2.NewIPAdvertisement(ip, false, ifs)
}
// nodesWithActiveSpeakers returns the list of nodes with active speakers.
func nodesWithActiveSpeakers(speakers map[string]bool) []string {
var ret []string
for node := range speakers {
ret = append(ret, node)
}
return ret
}
// activeEndpointExists returns true if at least one endpoint is active.
func activeEndpointExists(eps epslices.EpsOrSlices) bool {
switch eps.Type {
case epslices.Eps:
for _, subset := range eps.EpVal.Subsets {
if len(subset.Addresses) > 0 {
return true
}
}
case epslices.Slices:
for _, slice := range eps.SlicesVal {
for _, ep := range slice.Endpoints {
if !epslices.IsConditionServing(ep.Conditions) {
continue
}
return true
}
}
}
return false
}
func poolMatchesNodeL2(pool *config.Pool, node string) bool {
for _, adv := range pool.L2Advertisements {
if adv.Nodes[node] {
return true
}
}
return false
}
func speakersForPool(speakers map[string]bool, pool *config.Pool, nodes map[string]*v1.Node) map[string]bool {
res := map[string]bool{}
for s := range speakers {
if k8snodes.IsNetworkUnavailable(nodes[s]) {
continue
}
if poolMatchesNodeL2(pool, s) {
res[s] = true
}
}
return res
}