forked from cilium/cilium
/
k8s_watcher.go
1980 lines (1758 loc) · 63.3 KB
/
k8s_watcher.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2019 Authors of Cilium
//
// 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 (
"context"
"errors"
"fmt"
"net"
"net/url"
"os"
"strconv"
"sync"
"time"
"github.com/cilium/cilium/pkg/comparator"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/endpointmanager"
"github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/ipcache"
"github.com/cilium/cilium/pkg/k8s"
ciliumio "github.com/cilium/cilium/pkg/k8s/apis/cilium.io"
cilium_v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
clientset "github.com/cilium/cilium/pkg/k8s/client/clientset/versioned"
"github.com/cilium/cilium/pkg/k8s/informer"
k8smetrics "github.com/cilium/cilium/pkg/k8s/metrics"
"github.com/cilium/cilium/pkg/k8s/types"
k8sUtils "github.com/cilium/cilium/pkg/k8s/utils"
k8sversion "github.com/cilium/cilium/pkg/k8s/version"
"github.com/cilium/cilium/pkg/kvstore"
"github.com/cilium/cilium/pkg/labels"
"github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
bpfIPCache "github.com/cilium/cilium/pkg/maps/ipcache"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/node"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/serializer"
"github.com/cilium/cilium/pkg/service"
"github.com/cilium/cilium/pkg/source"
"github.com/cilium/cilium/pkg/spanstat"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
k8s_metrics "k8s.io/client-go/tools/metrics"
)
const (
k8sAPIGroupCRD = "CustomResourceDefinition"
k8sAPIGroupNodeV1Core = "core/v1::Node"
k8sAPIGroupNamespaceV1Core = "core/v1::Namespace"
k8sAPIGroupServiceV1Core = "core/v1::Service"
k8sAPIGroupEndpointV1Core = "core/v1::Endpoint"
k8sAPIGroupPodV1Core = "core/v1::Pods"
k8sAPIGroupNetworkingV1Core = "networking.k8s.io/v1::NetworkPolicy"
k8sAPIGroupIngressV1Beta1 = "extensions/v1beta1::Ingress"
k8sAPIGroupCiliumNetworkPolicyV2 = "cilium/v2::CiliumNetworkPolicy"
k8sAPIGroupCiliumNodeV2 = "cilium/v2::CiliumNode"
k8sAPIGroupCiliumEndpointV2 = "cilium/v2::CiliumEndpoint"
metricCNP = "CiliumNetworkPolicy"
metricEndpoint = "Endpoint"
metricIngress = "Ingress"
metricKNP = "NetworkPolicy"
metricNS = "Namespace"
metricCiliumNode = "CiliumNode"
metricCiliumEndpoint = "CiliumEndpoint"
metricPod = "Pod"
metricService = "Service"
metricCreate = "create"
metricDelete = "delete"
metricUpdate = "update"
)
var (
k8sCM = controller.NewManager()
importMetadataCache = ruleImportMetadataCache{
ruleImportMetadataMap: make(map[string]policyImportMetadata),
}
errIPCacheOwnedByNonK8s = fmt.Errorf("ipcache entry owned by kvstore or agent")
)
// ruleImportMetadataCache maps the unique identifier of a CiliumNetworkPolicy
// (namespace and name) to metadata about the importing of the rule into the
// agent's policy repository at the time said rule was imported (revision
// number, and if any error occurred while importing).
type ruleImportMetadataCache struct {
mutex lock.RWMutex
ruleImportMetadataMap map[string]policyImportMetadata
}
type policyImportMetadata struct {
revision uint64
policyImportError error
}
func (r *ruleImportMetadataCache) upsert(cnp *types.SlimCNP, revision uint64, importErr error) {
if cnp == nil {
return
}
meta := policyImportMetadata{
revision: revision,
policyImportError: importErr,
}
podNSName := k8sUtils.GetObjNamespaceName(&cnp.ObjectMeta)
r.mutex.Lock()
r.ruleImportMetadataMap[podNSName] = meta
r.mutex.Unlock()
}
func (r *ruleImportMetadataCache) delete(cnp *types.SlimCNP) {
if cnp == nil {
return
}
podNSName := k8sUtils.GetObjNamespaceName(&cnp.ObjectMeta)
r.mutex.Lock()
delete(r.ruleImportMetadataMap, podNSName)
r.mutex.Unlock()
}
func (r *ruleImportMetadataCache) get(cnp *types.SlimCNP) (policyImportMetadata, bool) {
if cnp == nil {
return policyImportMetadata{}, false
}
podNSName := k8sUtils.GetObjNamespaceName(&cnp.ObjectMeta)
r.mutex.RLock()
policyImportMeta, ok := r.ruleImportMetadataMap[podNSName]
r.mutex.RUnlock()
return policyImportMeta, ok
}
// k8sAPIGroupsUsed is a lockable map to hold which k8s API Groups we have
// enabled/in-use
// Note: We can replace it with a Go 1.9 map once we require that version
type k8sAPIGroupsUsed struct {
lock.RWMutex
apis map[string]bool
}
func (m *k8sAPIGroupsUsed) addAPI(api string) {
m.Lock()
defer m.Unlock()
if m.apis == nil {
m.apis = make(map[string]bool)
}
m.apis[api] = true
}
func (m *k8sAPIGroupsUsed) removeAPI(api string) {
m.Lock()
defer m.Unlock()
delete(m.apis, api)
}
func (m *k8sAPIGroupsUsed) getGroups() []string {
m.RLock()
defer m.RUnlock()
groups := make([]string, 0, len(m.apis))
for k := range m.apis {
groups = append(groups, k)
}
return groups
}
// k8sMetrics implements the LatencyMetric and ResultMetric interface from
// k8s client-go package
type k8sMetrics struct{}
func (*k8sMetrics) Observe(verb string, u url.URL, latency time.Duration) {
metrics.KubernetesAPIInteractions.WithLabelValues(u.Path, verb).Observe(latency.Seconds())
}
func (*k8sMetrics) Increment(code string, method string, host string) {
metrics.KubernetesAPICalls.WithLabelValues(host, method, code).Inc()
k8smetrics.LastInteraction.Reset()
}
func init() {
// Replace error handler with our own
runtime.ErrorHandlers = []func(error){
k8s.K8sErrorHandler,
}
k8sMetric := &k8sMetrics{}
k8s_metrics.Register(k8sMetric, k8sMetric)
}
// blockWaitGroupToSyncResources ensures that anything which waits on waitGroup
// waits until all objects of the specified resource stored in Kubernetes are
// received by the informer and processed by controller.
// Fatally exits if syncing these initial objects fails.
// If the given stop channel is closed, it does not fatal.
func (d *Daemon) blockWaitGroupToSyncResources(stop <-chan struct{}, informer cache.Controller, resourceName string) {
ch := make(chan struct{})
d.k8sResourceSyncedMu.Lock()
d.k8sResourceSynced[resourceName] = ch
d.k8sResourceSyncedMu.Unlock()
go func() {
scopedLog := log.WithField("kubernetesResource", resourceName)
scopedLog.Debug("waiting for cache to synchronize")
if ok := cache.WaitForCacheSync(stop, informer.HasSynced); !ok {
select {
case <-stop:
scopedLog.Debug("canceled cache synchronization")
// do not fatal if the channel was stopped
default:
// Fatally exit it resource fails to sync
scopedLog.Fatalf("failed to wait for cache to sync")
}
} else {
scopedLog.Debug("cache synced")
}
close(ch)
}()
}
// waitForCacheSync waits for k8s caches to be synchronized for the given
// resource. Returns once all resourcesNames are synchronized with cilium-agent.
func (d *Daemon) waitForCacheSync(resourceNames ...string) {
for _, resourceName := range resourceNames {
d.k8sResourceSyncedMu.RLock()
c, ok := d.k8sResourceSynced[resourceName]
d.k8sResourceSyncedMu.RUnlock()
if !ok {
continue
}
<-c
}
}
// initK8sSubsystem returns a channel for which it will be closed when all
// caches essential for daemon are synchronized.
func (d *Daemon) initK8sSubsystem() <-chan struct{} {
if err := d.EnableK8sWatcher(option.Config.K8sWatcherQueueSize); err != nil {
log.WithError(err).Fatal("Unable to establish connection to Kubernetes apiserver")
}
cachesSynced := make(chan struct{})
go func() {
log.Info("Waiting until all pre-existing resources related to policy have been received")
// Wait only for certain caches, but not all!
// We don't wait for nodes synchronization nor ingresses.
d.waitForCacheSync(
// To perform the service translation and have the BPF LB datapath
// with the right service -> backend (k8s endpoints) translation.
k8sAPIGroupServiceV1Core,
// To perform the service translation and have the BPF LB datapath
// with the right service -> backend (k8s endpoints) translation.
k8sAPIGroupEndpointV1Core,
// We need all network policies in place before restoring to make sure
// we are enforcing the correct policies for each endpoint before
// restarting.
k8sAPIGroupCiliumNetworkPolicyV2,
// We we need to know about all other nodes
k8sAPIGroupCiliumNodeV2,
// We need all network policies in place before restoring to make sure
// we are enforcing the correct policies for each endpoint before
// restarting.
k8sAPIGroupNetworkingV1Core,
// Namespaces can contain labels which are essential for endpoints
// being restored to have the right identity.
k8sAPIGroupNamespaceV1Core,
// Pods can contain labels which are essential for endpoints
// being restored to have the right identity.
k8sAPIGroupPodV1Core,
)
// CiliumEndpoint is used to synchronize the ipcache, wait for
// it unless it is disabled
if !option.Config.DisableCiliumEndpointCRD {
d.waitForCacheSync(k8sAPIGroupCiliumEndpointV2)
}
close(cachesSynced)
}()
go func() {
select {
case <-cachesSynced:
log.Info("All pre-existing resources related to policy have been received; continuing")
case <-time.After(option.Config.K8sSyncTimeout):
log.Fatalf("Timed out waiting for pre-existing resources related to policy to be received; exiting")
}
}()
return cachesSynced
}
// K8sEventReceived does metric accounting for each received Kubernetes event
func (d *Daemon) K8sEventReceived(scope string, action string, valid, equal bool) {
metrics.EventTSK8s.SetToCurrentTime()
k8smetrics.LastInteraction.Reset()
metrics.KubernetesEventReceived.WithLabelValues(scope, action, strconv.FormatBool(valid), strconv.FormatBool(equal)).Inc()
}
// EnableK8sWatcher watches for policy, services and endpoint changes on the Kubernetes
// api server defined in the receiver's daemon k8sClient.
// queueSize specifies the queue length used to serialize k8s events.
func (d *Daemon) EnableK8sWatcher(queueSize uint) error {
if !k8s.IsEnabled() {
log.Debug("Not enabling k8s event listener because k8s is not enabled")
return nil
}
log.Info("Enabling k8s event listener")
d.k8sAPIGroups.addAPI(k8sAPIGroupCRD)
ciliumNPClient := k8s.CiliumClient()
serKNPs := serializer.NewFunctionQueue(queueSize)
serSvcs := serializer.NewFunctionQueue(queueSize)
serEps := serializer.NewFunctionQueue(queueSize)
serIngresses := serializer.NewFunctionQueue(queueSize)
serCNPs := serializer.NewFunctionQueue(queueSize)
serPods := serializer.NewFunctionQueue(queueSize)
serNodes := serializer.NewFunctionQueue(queueSize)
serCiliumEndpoints := serializer.NewFunctionQueue(queueSize)
serNamespaces := serializer.NewFunctionQueue(queueSize)
_, policyController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().NetworkingV1().RESTClient(),
"networkpolicies", v1.NamespaceAll, fields.Everything()),
&networkingv1.NetworkPolicy{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricKNP, metricCreate, valid, equal) }()
if k8sNP := k8s.CopyObjToV1NetworkPolicy(obj); k8sNP != nil {
valid = true
serKNPs.Enqueue(func() error {
err := d.addK8sNetworkPolicyV1(k8sNP)
d.K8sEventProcessed(metricKNP, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricKNP, metricUpdate, valid, equal) }()
if oldK8sNP := k8s.CopyObjToV1NetworkPolicy(oldObj); oldK8sNP != nil {
valid = true
if newK8sNP := k8s.CopyObjToV1NetworkPolicy(newObj); newK8sNP != nil {
if k8s.EqualV1NetworkPolicy(oldK8sNP, newK8sNP) {
equal = true
return
}
serKNPs.Enqueue(func() error {
err := d.updateK8sNetworkPolicyV1(oldK8sNP, newK8sNP)
d.K8sEventProcessed(metricKNP, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricKNP, metricDelete, valid, equal) }()
k8sNP := k8s.CopyObjToV1NetworkPolicy(obj)
if k8sNP == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
k8sNP = k8s.CopyObjToV1NetworkPolicy(deletedObj.Obj)
if k8sNP == nil {
return
}
}
valid = true
serKNPs.Enqueue(func() error {
err := d.deleteK8sNetworkPolicyV1(k8sNP)
d.K8sEventProcessed(metricKNP, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToNetworkPolicy,
)
d.blockWaitGroupToSyncResources(wait.NeverStop, policyController, k8sAPIGroupNetworkingV1Core)
go policyController.Run(wait.NeverStop)
d.k8sAPIGroups.addAPI(k8sAPIGroupNetworkingV1Core)
_, svcController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().CoreV1().RESTClient(),
"services", v1.NamespaceAll, fields.Everything()),
&v1.Service{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricService, metricCreate, valid, equal) }()
if k8sSvc := k8s.CopyObjToV1Services(obj); k8sSvc != nil {
valid = true
serSvcs.Enqueue(func() error {
err := d.addK8sServiceV1(k8sSvc)
d.K8sEventProcessed(metricService, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricService, metricUpdate, valid, equal) }()
if oldk8sSvc := k8s.CopyObjToV1Services(oldObj); oldk8sSvc != nil {
valid = true
if newk8sSvc := k8s.CopyObjToV1Services(newObj); newk8sSvc != nil {
if k8s.EqualV1Services(oldk8sSvc, newk8sSvc) {
equal = true
return
}
serSvcs.Enqueue(func() error {
err := d.updateK8sServiceV1(oldk8sSvc, newk8sSvc)
d.K8sEventProcessed(metricService, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricService, metricDelete, valid, equal) }()
k8sSvc := k8s.CopyObjToV1Services(obj)
if k8sSvc == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
k8sSvc = k8s.CopyObjToV1Services(deletedObj.Obj)
if k8sSvc == nil {
return
}
}
valid = true
serSvcs.Enqueue(func() error {
err := d.deleteK8sServiceV1(k8sSvc)
d.K8sEventProcessed(metricService, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToK8sService,
)
d.blockWaitGroupToSyncResources(wait.NeverStop, svcController, k8sAPIGroupServiceV1Core)
go svcController.Run(wait.NeverStop)
d.k8sAPIGroups.addAPI(k8sAPIGroupServiceV1Core)
_, endpointController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().CoreV1().RESTClient(),
"endpoints", v1.NamespaceAll,
fields.ParseSelectorOrDie(option.Config.K8sWatcherEndpointSelector),
),
&v1.Endpoints{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricCreate, valid, equal) }()
if k8sEP := k8s.CopyObjToV1Endpoints(obj); k8sEP != nil {
valid = true
serEps.Enqueue(func() error {
err := d.addK8sEndpointV1(k8sEP)
d.K8sEventProcessed(metricEndpoint, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricUpdate, valid, equal) }()
if oldk8sEP := k8s.CopyObjToV1Endpoints(oldObj); oldk8sEP != nil {
valid = true
if newk8sEP := k8s.CopyObjToV1Endpoints(newObj); newk8sEP != nil {
if k8s.EqualV1Endpoints(oldk8sEP, newk8sEP) {
equal = true
return
}
serEps.Enqueue(func() error {
err := d.updateK8sEndpointV1(oldk8sEP, newk8sEP)
d.K8sEventProcessed(metricEndpoint, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricDelete, valid, equal) }()
k8sEP := k8s.CopyObjToV1Endpoints(obj)
if k8sEP == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
k8sEP = k8s.CopyObjToV1Endpoints(deletedObj.Obj)
if k8sEP == nil {
return
}
}
valid = true
serEps.Enqueue(func() error {
err := d.deleteK8sEndpointV1(k8sEP)
d.K8sEventProcessed(metricEndpoint, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToK8sEndpoints,
)
d.blockWaitGroupToSyncResources(wait.NeverStop, endpointController, k8sAPIGroupEndpointV1Core)
go endpointController.Run(wait.NeverStop)
d.k8sAPIGroups.addAPI(k8sAPIGroupEndpointV1Core)
if option.Config.IsLBEnabled() {
_, ingressController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().ExtensionsV1beta1().RESTClient(),
"ingresses", v1.NamespaceAll, fields.Everything()),
&v1beta1.Ingress{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricCreate, valid, equal) }()
if k8sIngress := k8s.CopyObjToV1beta1Ingress(obj); k8sIngress != nil {
valid = true
serIngresses.Enqueue(func() error {
err := d.addIngressV1beta1(k8sIngress)
d.K8sEventProcessed(metricIngress, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricUpdate, valid, equal) }()
if oldk8sIngress := k8s.CopyObjToV1beta1Ingress(oldObj); oldk8sIngress != nil {
valid = true
if newk8sIngress := k8s.CopyObjToV1beta1Ingress(newObj); newk8sIngress != nil {
if k8s.EqualV1beta1Ingress(oldk8sIngress, newk8sIngress) {
equal = true
return
}
serIngresses.Enqueue(func() error {
err := d.updateIngressV1beta1(oldk8sIngress, newk8sIngress)
d.K8sEventProcessed(metricIngress, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricEndpoint, metricDelete, valid, equal) }()
k8sIngress := k8s.CopyObjToV1beta1Ingress(obj)
if k8sIngress == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
k8sIngress = k8s.CopyObjToV1beta1Ingress(deletedObj.Obj)
if k8sIngress == nil {
return
}
}
valid = true
serEps.Enqueue(func() error {
err := d.deleteIngressV1beta1(k8sIngress)
d.K8sEventProcessed(metricIngress, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToIngress,
)
d.blockWaitGroupToSyncResources(wait.NeverStop, ingressController, k8sAPIGroupIngressV1Beta1)
go ingressController.Run(wait.NeverStop)
d.k8sAPIGroups.addAPI(k8sAPIGroupIngressV1Beta1)
}
var (
cnpEventStore cache.Store
cnpConverterFunc informer.ConvertFunc
)
cnpStore := cache.NewStore(cache.DeletionHandlingMetaNamespaceKeyFunc)
switch {
case k8sversion.Capabilities().Patch:
// k8s >= 1.13 does not require a store to update CNP status so
// we don't even need to keep the status of a CNP with us.
cnpConverterFunc = k8s.ConvertToCNP
default:
cnpEventStore = cnpStore
cnpConverterFunc = k8s.ConvertToCNPWithStatus
}
ciliumV2Controller := informer.NewInformerWithStore(
cache.NewListWatchFromClient(ciliumNPClient.CiliumV2().RESTClient(),
"ciliumnetworkpolicies", v1.NamespaceAll, fields.Everything()),
&cilium_v2.CiliumNetworkPolicy{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCNP, metricCreate, valid, equal) }()
if cnp := k8s.CopyObjToV2CNP(obj); cnp != nil {
valid = true
serCNPs.Enqueue(func() error {
if cnp.RequiresDerivative() {
return nil
}
err := d.addCiliumNetworkPolicyV2(ciliumNPClient, cnpEventStore, cnp)
d.K8sEventProcessed(metricCNP, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCNP, metricUpdate, valid, equal) }()
if oldCNP := k8s.CopyObjToV2CNP(oldObj); oldCNP != nil {
valid = true
if newCNP := k8s.CopyObjToV2CNP(newObj); newCNP != nil {
if k8s.EqualV2CNP(oldCNP, newCNP) {
equal = true
return
}
serCNPs.Enqueue(func() error {
if newCNP.RequiresDerivative() {
return nil
}
err := d.updateCiliumNetworkPolicyV2(ciliumNPClient, cnpEventStore, oldCNP, newCNP)
d.K8sEventProcessed(metricCNP, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCNP, metricDelete, valid, equal) }()
cnp := k8s.CopyObjToV2CNP(obj)
if cnp == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
cnp = k8s.CopyObjToV2CNP(deletedObj.Obj)
if cnp == nil {
return
}
}
valid = true
serCNPs.Enqueue(func() error {
err := d.deleteCiliumNetworkPolicyV2(cnp)
d.K8sEventProcessed(metricCNP, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
},
},
cnpConverterFunc,
cnpStore,
)
d.blockWaitGroupToSyncResources(wait.NeverStop, ciliumV2Controller, k8sAPIGroupCiliumNetworkPolicyV2)
go ciliumV2Controller.Run(wait.NeverStop)
d.k8sAPIGroups.addAPI(k8sAPIGroupCiliumNetworkPolicyV2)
asyncControllers := sync.WaitGroup{}
asyncControllers.Add(1)
// CiliumNode objects are used for node discovery until the key-value
// store is connected
go func() {
var once sync.Once
for {
_, ciliumNodeInformer := informer.NewInformer(
cache.NewListWatchFromClient(ciliumNPClient.CiliumV2().RESTClient(),
"ciliumnodes", v1.NamespaceAll, fields.Everything()),
&cilium_v2.CiliumNode{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumNode, metricCreate, valid, equal) }()
if ciliumNode, ok := obj.(*cilium_v2.CiliumNode); ok {
valid = true
n := node.ParseCiliumNode(ciliumNode)
if n.IsLocal() {
return
}
serNodes.Enqueue(func() error {
d.nodeDiscovery.Manager.NodeUpdated(n)
d.K8sEventProcessed(metricCiliumNode, metricCreate, true)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumNode, metricUpdate, valid, equal) }()
if ciliumNode, ok := newObj.(*cilium_v2.CiliumNode); ok {
valid = true
n := node.ParseCiliumNode(ciliumNode)
if n.IsLocal() {
return
}
serNodes.Enqueue(func() error {
d.nodeDiscovery.Manager.NodeUpdated(n)
d.K8sEventProcessed(metricCiliumNode, metricUpdate, true)
return nil
}, serializer.NoRetry)
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumNode, metricDelete, valid, equal) }()
ciliumNode := k8s.CopyObjToCiliumNode(obj)
if ciliumNode == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
ciliumNode = k8s.CopyObjToCiliumNode(deletedObj.Obj)
if ciliumNode == nil {
return
}
}
valid = true
n := node.ParseCiliumNode(ciliumNode)
serNodes.Enqueue(func() error {
d.nodeDiscovery.Manager.NodeDeleted(n)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToCiliumNode,
)
isConnected := make(chan struct{})
// once isConnected is closed, it will stop waiting on caches to be
// synchronized.
d.blockWaitGroupToSyncResources(isConnected, ciliumNodeInformer, k8sAPIGroupCiliumNodeV2)
once.Do(func() {
// Signalize that we have put node controller in the wait group
// to sync resources.
asyncControllers.Done()
})
d.k8sAPIGroups.addAPI(k8sAPIGroupCiliumNodeV2)
go ciliumNodeInformer.Run(isConnected)
<-kvstore.Client().Connected()
close(isConnected)
log.Info("Connected to key-value store, stopping CiliumNode watcher")
d.k8sAPIGroups.removeAPI(k8sAPIGroupCiliumNodeV2)
// Create a new node controller when we are disconnected with the
// kvstore
<-kvstore.Client().Disconnected()
log.Info("Disconnected from key-value store, restarting CiliumNode watcher")
}
}()
asyncControllers.Add(1)
// CiliumEndpoint objects are used for ipcache discovery until the
// key-value store is connected
go func() {
var once sync.Once
for {
_, ciliumEndpointInformer := informer.NewInformer(
cache.NewListWatchFromClient(ciliumNPClient.CiliumV2().RESTClient(),
"ciliumendpoints", v1.NamespaceAll, fields.Everything()),
&cilium_v2.CiliumEndpoint{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumEndpoint, metricCreate, valid, equal) }()
if ciliumEndpoint, ok := obj.(*types.CiliumEndpoint); ok {
valid = true
endpoint := ciliumEndpoint.DeepCopy()
serCiliumEndpoints.Enqueue(func() error {
endpointUpdated(endpoint)
d.K8sEventProcessed(metricCiliumEndpoint, metricCreate, true)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumEndpoint, metricUpdate, valid, equal) }()
if ciliumEndpoint, ok := newObj.(*types.CiliumEndpoint); ok {
valid = true
endpoint := ciliumEndpoint.DeepCopy()
serCiliumEndpoints.Enqueue(func() error {
endpointUpdated(endpoint)
d.K8sEventProcessed(metricCiliumEndpoint, metricUpdate, true)
return nil
}, serializer.NoRetry)
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricCiliumEndpoint, metricDelete, valid, equal) }()
ciliumEndpoint := k8s.CopyObjToCiliumEndpoint(obj)
if ciliumEndpoint == nil {
deletedObj, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
// Delete was not observed by the watcher but is
// removed from kube-apiserver. This is the last
// known state and the object no longer exists.
ciliumEndpoint = k8s.CopyObjToCiliumEndpoint(deletedObj.Obj)
if ciliumEndpoint == nil {
return
}
}
valid = true
serCiliumEndpoints.Enqueue(func() error {
endpointDeleted(ciliumEndpoint)
return nil
}, serializer.NoRetry)
},
},
k8s.ConvertToCiliumEndpoint,
)
isConnected := make(chan struct{})
// once isConnected is closed, it will stop waiting on caches to be
// synchronized.
d.blockWaitGroupToSyncResources(isConnected, ciliumEndpointInformer, k8sAPIGroupCiliumEndpointV2)
once.Do(func() {
// Signalize that we have put node controller in the wait group
// to sync resources.
asyncControllers.Done()
})
d.k8sAPIGroups.addAPI(k8sAPIGroupCiliumEndpointV2)
go ciliumEndpointInformer.Run(isConnected)
<-kvstore.Client().Connected()
close(isConnected)
log.Info("Connected to key-value store, stopping CiliumEndpoint watcher")
d.k8sAPIGroups.removeAPI(k8sAPIGroupCiliumEndpointV2)
// Create a new node controller when we are disconnected with the
// kvstore
<-kvstore.Client().Disconnected()
log.Info("Disconnected from key-value store, restarting CiliumEndpoint watcher")
}
}()
asyncControllers.Add(1)
go func() {
var once sync.Once
for {
createPodController := func(fieldSelector fields.Selector) cache.Controller {
_, podController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().CoreV1().RESTClient(),
"pods", v1.NamespaceAll, fieldSelector),
&v1.Pod{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricPod, metricCreate, valid, equal) }()
if pod := k8s.CopyObjToV1Pod(obj); pod != nil {
valid = true
serPods.Enqueue(func() error {
err := d.addK8sPodV1(pod)
d.K8sEventProcessed(metricPod, metricCreate, err == nil)
return nil
}, serializer.NoRetry)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricPod, metricUpdate, valid, equal) }()
if oldPod := k8s.CopyObjToV1Pod(oldObj); oldPod != nil {
valid = true
if newPod := k8s.CopyObjToV1Pod(newObj); newPod != nil {
if k8s.EqualV1Pod(oldPod, newPod) {
equal = true
return
}
serPods.Enqueue(func() error {
err := d.updateK8sPodV1(oldPod, newPod)
d.K8sEventProcessed(metricPod, metricUpdate, err == nil)
return nil
}, serializer.NoRetry)
}
}
},
DeleteFunc: func(obj interface{}) {
var valid, equal bool
defer func() { d.K8sEventReceived(metricPod, metricDelete, valid, equal) }()
if pod := k8s.CopyObjToV1Pod(obj); pod != nil {
valid = true
serPods.Enqueue(func() error {
err := d.deleteK8sPodV1(pod)
d.K8sEventProcessed(metricPod, metricDelete, err == nil)
return nil
}, serializer.NoRetry)
}
},
},
k8s.ConvertToPod,
)
return podController
}
podController := createPodController(fields.Everything())
isConnected := make(chan struct{})
// once isConnected is closed, it will stop waiting on caches to be
// synchronized.
d.blockWaitGroupToSyncResources(isConnected, podController, k8sAPIGroupPodV1Core)
once.Do(func() {
asyncControllers.Done()
d.k8sAPIGroups.addAPI(k8sAPIGroupPodV1Core)
})
go podController.Run(isConnected)
if !option.Config.K8sEventHandover {
return
}
// Replace pod controller by only receiving events from our own
// node once we are connected to the kvstore.
<-kvstore.Client().Connected()
close(isConnected)
log.WithField(logfields.Node, node.GetName()).Info("Connected to KVStore, watching for pod events on node")
// Only watch for pod events for our node.
podController = createPodController(fields.ParseSelectorOrDie("spec.nodeName=" + node.GetName()))
isConnected = make(chan struct{})
go podController.Run(isConnected)
// Create a new pod controller when we are disconnected with the
// kvstore
<-kvstore.Client().Disconnected()
close(isConnected)
log.Info("Disconnected from KVStore, watching for pod events all nodes")
}
}()