-
Notifications
You must be signed in to change notification settings - Fork 492
/
service_control.go
279 lines (246 loc) · 9.14 KB
/
service_control.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
// Copyright 2018 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package controller
import (
"context"
"fmt"
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
coreinformers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
apiequality "k8s.io/apimachinery/pkg/api/equality"
)
// ExternalTrafficPolicy denotes if this Service desires to route external traffic to node-local or cluster-wide endpoints.
var ExternalTrafficPolicy string
// ServiceControlInterface manages Services used in TidbCluster
type ServiceControlInterface interface {
CreateService(runtime.Object, *corev1.Service) error
UpdateService(runtime.Object, *corev1.Service) (*corev1.Service, error)
DeleteService(runtime.Object, *corev1.Service) error
SyncComponentService(tc runtime.Object, newSvc *corev1.Service, oldService *corev1.Service, setClusterIP bool) (*corev1.Service, error)
}
type realServiceControl struct {
kubeCli kubernetes.Interface
svcLister corelisters.ServiceLister
recorder record.EventRecorder
}
// NewRealServiceControl creates a new ServiceControlInterface
func NewRealServiceControl(kubeCli kubernetes.Interface, svcLister corelisters.ServiceLister, recorder record.EventRecorder) ServiceControlInterface {
return &realServiceControl{
kubeCli,
svcLister,
recorder,
}
}
func (c *realServiceControl) CreateService(controller runtime.Object, svc *corev1.Service) error {
controllerMo, ok := controller.(metav1.Object)
if !ok {
return fmt.Errorf("%T is not a metav1.Object, cannot call setControllerReference", controller)
}
kind := controller.GetObjectKind().GroupVersionKind().Kind
name := controllerMo.GetName()
namespace := controllerMo.GetNamespace()
_, err := c.kubeCli.CoreV1().Services(namespace).Create(context.TODO(), svc, metav1.CreateOptions{})
c.recordServiceEvent("create", name, kind, controller, svc, err)
return err
}
func (c *realServiceControl) UpdateService(controller runtime.Object, svc *corev1.Service) (*corev1.Service, error) {
controllerMo, ok := controller.(metav1.Object)
if !ok {
return nil, fmt.Errorf("%T is not a metav1.Object, cannot call setControllerReference", controller)
}
kind := controller.GetObjectKind().GroupVersionKind().Kind
name := controllerMo.GetName()
namespace := controllerMo.GetNamespace()
svcName := svc.GetName()
svcSpec := svc.Spec.DeepCopy()
var updateSvc *corev1.Service
err := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
var updateErr error
updateSvc, updateErr = c.kubeCli.CoreV1().Services(namespace).Update(context.TODO(), svc, metav1.UpdateOptions{})
if updateErr == nil {
klog.Infof("update Service: [%s/%s] successfully, kind: %s, name: %s", namespace, svcName, kind, name)
return nil
}
if updated, err := c.svcLister.Services(namespace).Get(svcName); err != nil {
utilruntime.HandleError(fmt.Errorf("error getting updated Service %s/%s from lister: %v", namespace, svcName, err))
} else {
svc = updated.DeepCopy()
svc.Spec = *svcSpec
}
return updateErr
})
return updateSvc, err
}
func (c *realServiceControl) DeleteService(controller runtime.Object, svc *corev1.Service) error {
controllerMo, ok := controller.(metav1.Object)
if !ok {
return fmt.Errorf("%T is not a metav1.Object, cannot call setControllerReference", controller)
}
kind := controller.GetObjectKind().GroupVersionKind().Kind
name := controllerMo.GetName()
namespace := controllerMo.GetNamespace()
err := c.kubeCli.CoreV1().Services(namespace).Delete(context.TODO(), svc.Name, metav1.DeleteOptions{})
c.recordServiceEvent("delete", name, kind, controller, svc, err)
return err
}
func (c *realServiceControl) recordServiceEvent(verb, name, kind string, object runtime.Object, svc *corev1.Service, err error) {
svcName := svc.GetName()
if err == nil {
reason := fmt.Sprintf("Successful%s", strings.Title(verb))
msg := fmt.Sprintf("%s Service %s in %s %s successful",
strings.ToLower(verb), svcName, kind, name)
c.recorder.Event(object, corev1.EventTypeNormal, reason, msg)
} else {
reason := fmt.Sprintf("Failed%s", strings.Title(verb))
msg := fmt.Sprintf("%s Service %s in %s %s failed error: %s",
strings.ToLower(verb), svcName, kind, name, err)
c.recorder.Event(object, corev1.EventTypeWarning, reason, msg)
}
}
func (c *realServiceControl) SyncComponentService(tc runtime.Object, newSvc, oldSvc *corev1.Service, setClusterIP bool) (*corev1.Service, error) {
equal, err := ServiceEqual(newSvc, oldSvc)
if err != nil {
return nil, err
}
if newSvc == nil || oldSvc == nil {
return nil, fmt.Errorf("ServiceAnnLabelEqual: newservice or oldService is nil")
}
if newSvc.Annotations == nil {
newSvc.Annotations = map[string]string{}
}
if oldSvc.Annotations == nil {
oldSvc.Annotations = map[string]string{}
}
if newSvc.Labels == nil {
newSvc.Labels = map[string]string{}
}
if oldSvc.Labels == nil {
oldSvc.Labels = map[string]string{}
}
delete(oldSvc.Annotations, LastAppliedConfigAnnotation)
annoEqual := apiequality.Semantic.DeepEqual(newSvc.Annotations, oldSvc.Annotations)
labelEqual := apiequality.Semantic.DeepEqual(newSvc.Labels, oldSvc.Labels)
if !equal || !annoEqual || !labelEqual {
svc := *oldSvc
svc.Spec = newSvc.Spec
err = SetServiceLastAppliedConfigAnnotation(&svc)
if err != nil {
return nil, err
}
if setClusterIP {
svc.Spec.ClusterIP = oldSvc.Spec.ClusterIP
}
for k, v := range newSvc.Annotations {
svc.Annotations[k] = v
}
for k, v := range newSvc.Labels {
svc.Labels[k] = v
}
return c.UpdateService(tc, &svc)
}
return nil, nil
}
var _ ServiceControlInterface = &realServiceControl{}
// FakeServiceControl is a fake ServiceControlInterface
type FakeServiceControl struct {
SvcLister corelisters.ServiceLister
SvcIndexer cache.Indexer
EpsIndexer cache.Indexer
createServiceTracker RequestTracker
updateServiceTracker RequestTracker
deleteStatefulSetTracker RequestTracker
}
// NewFakeServiceControl returns a FakeServiceControl
func NewFakeServiceControl(svcInformer coreinformers.ServiceInformer, epsInformer coreinformers.EndpointsInformer) *FakeServiceControl {
return &FakeServiceControl{
svcInformer.Lister(),
svcInformer.Informer().GetIndexer(),
epsInformer.Informer().GetIndexer(),
RequestTracker{},
RequestTracker{},
RequestTracker{},
}
}
// SetCreateServiceError sets the error attributes of createServiceTracker
func (c *FakeServiceControl) SetCreateServiceError(err error, after int) {
c.createServiceTracker.SetError(err).SetAfter(after)
}
// SetUpdateServiceError sets the error attributes of updateServiceTracker
func (c *FakeServiceControl) SetUpdateServiceError(err error, after int) {
c.updateServiceTracker.SetError(err).SetAfter(after)
}
// SetDeleteServiceError sets the error attributes of deleteServiceTracker
func (c *FakeServiceControl) SetDeleteServiceError(err error, after int) {
c.deleteStatefulSetTracker.SetError(err).SetAfter(after)
}
// CreateService adds the service to SvcIndexer
func (c *FakeServiceControl) CreateService(_ runtime.Object, svc *corev1.Service) error {
defer c.createServiceTracker.Inc()
if c.createServiceTracker.ErrorReady() {
defer c.createServiceTracker.Reset()
return c.createServiceTracker.GetError()
}
err := c.SvcIndexer.Add(svc)
if err != nil {
return err
}
// add a new endpoint to indexer if svc has selector
if svc.Spec.Selector != nil {
eps := &corev1.Endpoints{
ObjectMeta: metav1.ObjectMeta{
Name: svc.Name,
Namespace: svc.Namespace,
},
}
return c.EpsIndexer.Add(eps)
}
return nil
}
// UpdateService updates the service of SvcIndexer
func (c *FakeServiceControl) UpdateService(_ runtime.Object, svc *corev1.Service) (*corev1.Service, error) {
defer c.updateServiceTracker.Inc()
if c.updateServiceTracker.ErrorReady() {
defer c.updateServiceTracker.Reset()
return nil, c.updateServiceTracker.GetError()
}
if svc.Spec.Selector != nil {
eps := &corev1.Endpoints{
ObjectMeta: metav1.ObjectMeta{
Name: svc.Name,
Namespace: svc.Namespace,
},
}
err := c.EpsIndexer.Update(eps)
if err != nil {
return nil, err
}
}
return svc, c.SvcIndexer.Update(svc)
}
func (c *FakeServiceControl) SyncComponentService(tc runtime.Object, svc *corev1.Service, _ *corev1.Service, _ bool) (*corev1.Service, error) {
return c.UpdateService(tc, svc)
}
// DeleteService deletes the service of SvcIndexer
func (c *FakeServiceControl) DeleteService(_ runtime.Object, _ *corev1.Service) error {
return nil
}
var _ ServiceControlInterface = &FakeServiceControl{}