/
k8s_service_sync.go
237 lines (211 loc) · 7.08 KB
/
k8s_service_sync.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
// Copyright 2018 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 (
"time"
"github.com/cilium/cilium/pkg/k8s"
"github.com/cilium/cilium/pkg/k8s/informer"
"github.com/cilium/cilium/pkg/kvstore/store"
"github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/service"
"github.com/sirupsen/logrus"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
)
var (
k8sSvcCache = k8s.NewServiceCache()
// k8sSvcCacheSynced is used do signalize when all services are synced with
// k8s.
k8sSvcCacheSynced = make(chan struct{})
servicesStore *store.SharedStore
)
func k8sServiceHandler() {
for {
event, ok := <-k8sSvcCache.Events
if !ok {
return
}
svc := k8s.NewClusterService(event.ID, event.Service, event.Endpoints)
svc.Cluster = option.Config.ClusterName
log.WithFields(logrus.Fields{
logfields.K8sSvcName: event.ID.Name,
logfields.K8sNamespace: event.ID.Namespace,
"action": event.Action.String(),
"service": event.Service.String(),
"endpoints": event.Endpoints.String(),
"shared": event.Service.Shared,
}).Debug("Kubernetes service definition changed")
if !event.Service.Shared {
// The annotation may have been added, delete an eventual existing service
servicesStore.DeleteLocalKey(&svc)
continue
}
switch event.Action {
case k8s.UpdateService, k8s.UpdateIngress:
servicesStore.UpdateLocalKeySync(&svc)
case k8s.DeleteService, k8s.DeleteIngress:
servicesStore.DeleteLocalKey(&svc)
}
}
}
func startSynchronizingServices() {
log.Info("Starting to synchronize k8s services to kvstore...")
readyChan := make(chan struct{}, 0)
go func() {
store, err := store.JoinSharedStore(store.Configuration{
Prefix: service.ServiceStorePrefix,
KeyCreator: func() store.Key {
return &service.ClusterService{}
},
SynchronizationInterval: 5 * time.Minute,
})
if err != nil {
log.WithError(err).Fatal("Unable to join kvstore store to announce services")
}
servicesStore = store
close(readyChan)
}()
// Watch for v1.Service changes and push changes into ServiceCache
_, svcController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().CoreV1().RESTClient(),
"services", v1.NamespaceAll, fields.Everything()),
&v1.Service{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
if k8sSvc := k8s.CopyObjToV1Services(obj); k8sSvc != nil {
log.Debugf("Received service addition %+v", k8sSvc)
k8sSvcCache.UpdateService(k8sSvc)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
if oldk8sSvc := k8s.CopyObjToV1Services(oldObj); oldk8sSvc != nil {
if newk8sSvc := k8s.CopyObjToV1Services(newObj); newk8sSvc != nil {
if k8s.EqualV1Services(oldk8sSvc, newk8sSvc) {
return
}
log.Debugf("Received service update %+v", newk8sSvc)
k8sSvcCache.UpdateService(newk8sSvc)
}
}
},
DeleteFunc: func(obj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
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
}
}
log.Debugf("Received service deletion %+v", k8sSvc)
k8sSvcCache.DeleteService(k8sSvc)
},
},
k8s.ConvertToK8sService,
)
go svcController.Run(wait.NeverStop)
// Watch for v1.Endpoints changes and push changes into ServiceCache
_, endpointController := informer.NewInformer(
cache.NewListWatchFromClient(k8s.Client().CoreV1().RESTClient(),
"endpoints", v1.NamespaceAll,
// Don't get any events from kubernetes endpoints.
fields.ParseSelectorOrDie("metadata.name!=kube-scheduler,metadata.name!=kube-controller-manager"),
),
&v1.Endpoints{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
if k8sEP := k8s.CopyObjToV1Endpoints(obj); k8sEP != nil {
k8sSvcCache.UpdateEndpoints(k8sEP)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
if oldk8sEP := k8s.CopyObjToV1Endpoints(oldObj); oldk8sEP != nil {
if newk8sEP := k8s.CopyObjToV1Endpoints(newObj); newk8sEP != nil {
if k8s.EqualV1Endpoints(oldk8sEP, newk8sEP) {
return
}
k8sSvcCache.UpdateEndpoints(newk8sEP)
}
}
},
DeleteFunc: func(obj interface{}) {
metrics.EventTSK8s.SetToCurrentTime()
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
}
}
k8sSvcCache.DeleteEndpoints(k8sEP)
},
},
k8s.ConvertToK8sEndpoints,
)
go endpointController.Run(wait.NeverStop)
go func() {
cache.WaitForCacheSync(wait.NeverStop, svcController.HasSynced)
close(k8sSvcCacheSynced)
cache.WaitForCacheSync(wait.NeverStop, endpointController.HasSynced)
}()
go func() {
<-readyChan
log.Info("Starting to synchronize Kubernetes services to kvstore")
k8sServiceHandler()
}()
}
// serviceGetter is a wrapper for 2 k8sCaches, its intention is for
// `shortCutK8sCache` to be used until `k8sSvcCacheSynced` is closed, for which
// `k8sCache` is started to be used.
type serviceGetter struct {
shortCutK8sCache k8s.ServiceIPGetter
k8sCache k8s.ServiceIPGetter
}
// GetServiceIP returns the result of GetServiceIP for `s.shortCutK8sCache`
// until `k8sSvcCacheSynced` is closed. This is helpful as we can have a
// shortcut of `s.k8sCache` since we can pre-populate `s.shortCutK8sCache` with
// the entries that we need until `s.k8sCache` is synchronized with kubernetes.
func (s *serviceGetter) GetServiceIP(svcID k8s.ServiceID) *loadbalancer.L3n4Addr {
select {
case <-k8sSvcCacheSynced:
return s.k8sCache.GetServiceIP(svcID)
default:
return s.shortCutK8sCache.GetServiceIP(svcID)
}
}