-
Notifications
You must be signed in to change notification settings - Fork 442
/
service.go
475 lines (417 loc) · 12 KB
/
service.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
package controller
import (
"context"
"fmt"
"net"
"strings"
"time"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"github.com/kubeovn/kube-ovn/pkg/util"
)
type vpcService struct {
Vips []string
Vpc string
Protocol v1.Protocol
Svc *v1.Service
}
func (c *Controller) enqueueAddService(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
c.updateEndpointQueue.Add(key)
svc := obj.(*v1.Service)
if c.config.EnableNP {
var netpols []string
if netpols, err = c.svcMatchNetworkPolicies(svc); err != nil {
utilruntime.HandleError(err)
return
}
for _, np := range netpols {
c.updateNpQueue.Add(np)
}
}
if c.config.EnableLbSvc {
klog.V(3).Infof("enqueue add service %s", key)
c.addServiceQueue.Add(key)
}
}
func (c *Controller) enqueueDeleteService(obj interface{}) {
svc := obj.(*v1.Service)
//klog.V(3).Infof("enqueue delete service %s/%s", svc.Namespace, svc.Name)
klog.Infof("enqueue delete service %s/%s", svc.Namespace, svc.Name)
vip, ok := svc.Annotations[util.SwitchLBRuleVipsAnnotation]
if ok || svc.Spec.ClusterIP != v1.ClusterIPNone && svc.Spec.ClusterIP != "" {
if c.config.EnableNP {
var netpols []string
var err error
if netpols, err = c.svcMatchNetworkPolicies(svc); err != nil {
utilruntime.HandleError(err)
return
}
for _, np := range netpols {
c.updateNpQueue.Add(np)
}
}
ips := util.ServiceClusterIPs(*svc)
if ok {
ips = strings.Split(vip, ",")
}
for _, port := range svc.Spec.Ports {
vpcSvc := &vpcService{
Protocol: port.Protocol,
Vpc: svc.Annotations[util.VpcAnnotation],
Svc: svc,
}
for _, ip := range ips {
vpcSvc.Vips = append(vpcSvc.Vips, util.JoinHostPort(ip, port.Port))
}
klog.Infof("delete vpc service %v", vpcSvc)
c.deleteServiceQueue.Add(vpcSvc)
}
}
}
func (c *Controller) enqueueUpdateService(old, new interface{}) {
oldSvc := old.(*v1.Service)
newSvc := new.(*v1.Service)
if oldSvc.ResourceVersion == newSvc.ResourceVersion {
return
}
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(new); err != nil {
utilruntime.HandleError(err)
return
}
klog.V(3).Infof("enqueue update service %s", key)
c.updateServiceQueue.Add(key)
}
func (c *Controller) runAddServiceWorker() {
for c.processNextAddServiceWorkItem() {
}
}
func (c *Controller) runDeleteServiceWorker() {
for c.processNextDeleteServiceWorkItem() {
}
}
func (c *Controller) runUpdateServiceWorker() {
for c.processNextUpdateServiceWorkItem() {
}
}
func (c *Controller) processNextAddServiceWorkItem() bool {
obj, shutdown := c.addServiceQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.addServiceQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.addServiceQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleAddService(key); err != nil {
c.addServiceQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.addServiceQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextDeleteServiceWorkItem() bool {
obj, shutdown := c.deleteServiceQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.deleteServiceQueue.Done(obj)
var vpcSvc *vpcService
var ok bool
if vpcSvc, ok = obj.(*vpcService); !ok {
c.deleteServiceQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected vpcService in workqueue but got %#v", obj))
return nil
}
if err := c.handleDeleteService(vpcSvc); err != nil {
c.deleteServiceQueue.AddRateLimited(obj)
return fmt.Errorf("error syncing '%v': %s, requeuing", vpcSvc.Vips, err.Error())
}
c.deleteServiceQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextUpdateServiceWorkItem() bool {
obj, shutdown := c.updateServiceQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.updateServiceQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.updateServiceQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleUpdateService(key); err != nil {
c.updateServiceQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.updateServiceQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) handleDeleteService(service *vpcService) error {
svcs, err := c.servicesLister.Services(v1.NamespaceAll).List(labels.Everything())
if err != nil {
klog.Errorf("failed to list svc, %v", err)
return err
}
vpcLbConfig := c.GenVpcLoadBalancer(service.Vpc)
var vpcLB [2]string
switch service.Protocol {
case v1.ProtocolTCP:
vpcLB = [2]string{vpcLbConfig.TcpLoadBalancer, vpcLbConfig.TcpSessLoadBalancer}
case v1.ProtocolUDP:
vpcLB = [2]string{vpcLbConfig.UdpLoadBalancer, vpcLbConfig.UdpSessLoadBalancer}
case v1.ProtocolSCTP:
vpcLB = [2]string{vpcLbConfig.SctpLoadBalancer, vpcLbConfig.SctpSessLoadBalancer}
}
for _, vip := range service.Vips {
var found bool
ip := parseVipAddr(vip)
for _, svc := range svcs {
if util.ContainsString(util.ServiceClusterIPs(*svc), ip) {
found = true
break
}
}
if found {
continue
}
for _, lb := range vpcLB {
if err := c.ovnLegacyClient.DeleteLoadBalancerVip(vip, lb); err != nil {
klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err)
return err
}
}
}
if service.Svc.Spec.Type == v1.ServiceTypeLoadBalancer && c.config.EnableLbSvc {
if err := c.deleteLbSvc(service.Svc); err != nil {
klog.Errorf("failed to delete service %s, %v", service.Svc.Name, err)
return err
}
}
return nil
}
func (c *Controller) handleUpdateService(key string) error {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
klog.Infof("update svc %s/%s", namespace, name)
svc, err := c.servicesLister.Services(namespace).Get(name)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
var ips []string
if vip, ok := svc.Annotations[util.SwitchLBRuleVipsAnnotation]; ok {
ips = strings.Split(vip, ",")
} else {
ips = util.ServiceClusterIPs(*svc)
}
vpcName := svc.Annotations[util.VpcAnnotation]
if vpcName == "" {
vpcName = util.DefaultVpc
}
vpc, err := c.vpcsLister.Get(vpcName)
if err != nil {
klog.Errorf("failed to get vpc %s of lb, %v", vpcName, err)
return err
}
tcpLb, udpLb, sctpLb := vpc.Status.TcpLoadBalancer, vpc.Status.UdpLoadBalancer, vpc.Status.SctpLoadBalancer
oTcpLb, oUdpLb, oSctpLb := vpc.Status.TcpSessionLoadBalancer, vpc.Status.UdpSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer
if svc.Spec.SessionAffinity == v1.ServiceAffinityClientIP {
tcpLb, udpLb, sctpLb, oTcpLb, oUdpLb, oSctpLb = oTcpLb, oUdpLb, oSctpLb, tcpLb, udpLb, sctpLb
}
var tcpVips, udpVips, sctpVips []string
for _, port := range svc.Spec.Ports {
for _, ip := range ips {
switch port.Protocol {
case v1.ProtocolTCP:
tcpVips = append(tcpVips, util.JoinHostPort(ip, port.Port))
case v1.ProtocolUDP:
udpVips = append(udpVips, util.JoinHostPort(ip, port.Port))
case v1.ProtocolSCTP:
sctpVips = append(sctpVips, util.JoinHostPort(ip, port.Port))
}
}
}
// for service update
updateVip := func(lb, oLb string, svcVips []string) error {
vips, err := c.ovnLegacyClient.GetLoadBalancerVips(lb)
if err != nil {
klog.Errorf("failed to get vips of LB %s: %v", lb, err)
return err
}
klog.V(3).Infof("existing vips of LB %s: %v", lb, vips)
for _, vip := range svcVips {
if err = c.ovnLegacyClient.DeleteLoadBalancerVip(vip, oLb); err != nil {
klog.Errorf("failed to delete vip %s from LB %s: %v", vip, oLb, err)
return err
}
if _, ok := vips[vip]; !ok {
klog.Infof("add vip %s to LB %s", vip, lb)
c.updateEndpointQueue.Add(key)
break
}
}
for vip := range vips {
if ip := parseVipAddr(vip); util.ContainsString(ips, ip) && !util.IsStringIn(vip, svcVips) {
klog.Infof("remove stale vip %s from LB %s", vip, lb)
if err = c.ovnLegacyClient.DeleteLoadBalancerVip(vip, lb); err != nil {
klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err)
return err
}
}
}
if vips, err = c.ovnLegacyClient.GetLoadBalancerVips(oLb); err != nil {
klog.Errorf("failed to get vips of LB %s: %v", oLb, err)
return err
}
klog.V(3).Infof("existing vips of LB %s: %v", oLb, vips)
for vip := range vips {
if ip := parseVipAddr(vip); util.ContainsString(ips, ip) {
klog.Infof("remove stale vip %s from LB %s", vip, oLb)
if err = c.ovnLegacyClient.DeleteLoadBalancerVip(vip, oLb); err != nil {
klog.Errorf("failed to delete vip %s from LB %s: %v", vip, oLb, err)
return err
}
}
}
return nil
}
if err = updateVip(tcpLb, oTcpLb, tcpVips); err != nil {
return err
}
if err = updateVip(udpLb, oUdpLb, udpVips); err != nil {
return err
}
if err = updateVip(sctpLb, oSctpLb, sctpVips); err != nil {
return err
}
return nil
}
// Parse key of map, [fd00:10:96::11c9]:10665 for example
func parseVipAddr(vip string) string {
host, _, err := net.SplitHostPort(vip)
if err != nil {
klog.Errorf("failed to parse vip %q: %v", vip, err)
return ""
}
return host
}
func (c *Controller) handleAddService(key string) error {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
svc, err := c.servicesLister.Services(namespace).Get(name)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if svc.Spec.Type != v1.ServiceTypeLoadBalancer || !c.config.EnableLbSvc {
return nil
}
klog.Infof("add svc %s/%s", namespace, name)
if err = c.validateSvc(svc); err != nil {
klog.Errorf("failed to validate lb svc, %v", err)
return err
}
if err = c.checkAttachNetwork(svc); err != nil {
klog.Errorf("failed to check attachment network, %v", err)
return err
}
if err = c.createLbSvcPod(svc); err != nil {
klog.Errorf("failed to create lb svc pod, %v", err)
return err
}
var pod *v1.Pod
for {
pod, err = c.getLbSvcPod(name, namespace)
if err != nil {
klog.Errorf("wait lb svc pod to running, %v", err)
time.Sleep(1 * time.Second)
}
if pod != nil {
break
}
// It's important here to check existing of svc, used to break the loop.
_, err = c.servicesLister.Services(namespace).Get(name)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
}
loadBalancerIP, err := c.getPodAttachIP(pod, svc)
if err != nil {
klog.Errorf("failed to get loadBalancerIP: %v", err)
return err
}
newSvc, err := c.servicesLister.Services(namespace).Get(name)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
var ingress v1.LoadBalancerIngress
ingress.IP = loadBalancerIP
newSvc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{ingress}
var updateSvc *v1.Service
if updateSvc, err = c.config.KubeClient.CoreV1().Services(namespace).UpdateStatus(context.Background(), newSvc, metav1.UpdateOptions{}); err != nil {
klog.Errorf("update service %s/%s status failed: %v", namespace, name, err)
return err
}
if err := c.updatePodAttachNets(pod, updateSvc); err != nil {
klog.Errorf("update service %s/%s attachment network failed: %v", namespace, name, err)
return err
}
return nil
}