-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathpump_member_manager.go
487 lines (432 loc) · 12.5 KB
/
pump_member_manager.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
// Copyright 2019 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 member
import (
"fmt"
"strings"
"github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
"github.com/pingcap/tidb-operator/pkg/controller"
"github.com/pingcap/tidb-operator/pkg/label"
"github.com/pingcap/tidb-operator/pkg/manager"
apps "k8s.io/api/apps/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
v1 "k8s.io/client-go/listers/apps/v1"
corelisters "k8s.io/client-go/listers/core/v1"
glog "k8s.io/klog"
)
const (
defaultPumpLogLevel = "info"
)
type pumpMemberManager struct {
setControl controller.StatefulSetControlInterface
svcControl controller.ServiceControlInterface
typedControl controller.TypedControlInterface
cmControl controller.ConfigMapControlInterface
setLister v1.StatefulSetLister
svcLister corelisters.ServiceLister
cmLister corelisters.ConfigMapLister
podLister corelisters.PodLister
}
// NewPumpMemberManager returns a controller to reconcile pump clusters
func NewPumpMemberManager(
setControl controller.StatefulSetControlInterface,
svcControl controller.ServiceControlInterface,
typedControl controller.TypedControlInterface,
cmControl controller.ConfigMapControlInterface,
setLister v1.StatefulSetLister,
svcLister corelisters.ServiceLister,
cmLister corelisters.ConfigMapLister,
podLister corelisters.PodLister) manager.Manager {
return &pumpMemberManager{
setControl,
svcControl,
typedControl,
cmControl,
setLister,
svcLister,
cmLister,
podLister,
}
}
func (pmm *pumpMemberManager) Sync(tc *v1alpha1.TidbCluster) error {
if tc.Spec.Pump == nil {
return nil
}
if err := pmm.syncHeadlessService(tc); err != nil {
return err
}
return pmm.syncPumpStatefulSetForTidbCluster(tc)
}
//syncPumpStatefulSetForTidbCluster sync statefulset status of pump to tidbcluster
func (pmm *pumpMemberManager) syncPumpStatefulSetForTidbCluster(tc *v1alpha1.TidbCluster) error {
oldPumpSetTemp, err := pmm.setLister.StatefulSets(tc.Namespace).Get(controller.PumpMemberName(tc.Name))
if err != nil && !errors.IsNotFound(err) {
return err
}
notFound := errors.IsNotFound(err)
oldPumpSet := oldPumpSetTemp.DeepCopy()
cm, err := pmm.syncConfigMap(tc, oldPumpSet)
if err != nil {
return err
}
newPumpSet, err := getNewPumpStatefulSet(tc, cm)
if err != nil {
return err
}
if notFound {
err = SetStatefulSetLastAppliedConfigAnnotation(newPumpSet)
if err != nil {
return err
}
return pmm.setControl.CreateStatefulSet(tc, newPumpSet)
}
if err := pmm.syncTiDBClusterStatus(tc, oldPumpSet); err != nil {
glog.Errorf("failed to sync TidbCluster: [%s/%s]'s status, error: %v", tc.Namespace, tc.Name, err)
return err
}
return updateStatefulSet(pmm.setControl, tc, newPumpSet, oldPumpSet)
}
func (pmm *pumpMemberManager) syncTiDBClusterStatus(tc *v1alpha1.TidbCluster, set *apps.StatefulSet) error {
tc.Status.Pump.StatefulSet = &set.Status
upgrading, err := pmm.pumpStatefulSetIsUpgrading(set, tc)
if err != nil {
return err
}
if upgrading {
tc.Status.Pump.Phase = v1alpha1.UpgradePhase
} else {
tc.Status.Pump.Phase = v1alpha1.NormalPhase
}
//TODO: support sync pump members from PD.
// pumpStatus := map[string]v1alpha1.PumpMember{}
// tc.Status.Pump.Members = pumpStatus
return nil
}
func (pmm *pumpMemberManager) syncHeadlessService(tc *v1alpha1.TidbCluster) error {
newSvc := getNewPumpHeadlessService(tc)
oldSvc, err := pmm.svcLister.Services(newSvc.Namespace).Get(newSvc.Name)
if errors.IsNotFound(err) {
err = controller.SetServiceLastAppliedConfigAnnotation(newSvc)
if err != nil {
return err
}
return pmm.svcControl.CreateService(tc, newSvc)
}
if err != nil {
return err
}
equal, err := controller.ServiceEqual(newSvc, oldSvc)
if err != nil {
return err
}
isOrphan := metav1.GetControllerOf(oldSvc) == nil
if !equal || isOrphan {
svc := *oldSvc
svc.Spec = newSvc.Spec
err = controller.SetServiceLastAppliedConfigAnnotation(&svc)
if err != nil {
return err
}
// Adopt headless-service created by helm
if isOrphan {
svc.OwnerReferences = newSvc.OwnerReferences
svc.Labels = newSvc.Labels
}
_, err = pmm.svcControl.UpdateService(tc, &svc)
return err
}
return nil
}
func (pmm *pumpMemberManager) syncConfigMap(tc *v1alpha1.TidbCluster, set *appsv1.StatefulSet) (*corev1.ConfigMap, error) {
basePumpSpec, createPump := tc.BasePumpSpec()
if !createPump {
return nil, nil
}
newCm, err := getNewPumpConfigMap(tc)
if err != nil {
return nil, err
}
// In-place update should pick the name of currently in-use configmap if exists to avoid rolling-update if:
// - user switch strategy from RollingUpdate to In-place
// - the statefulset and configmap is created by other clients (e.g. helm)
if set != nil && basePumpSpec.ConfigUpdateStrategy() == v1alpha1.ConfigUpdateStrategyInPlace {
inUseName := FindConfigMapVolume(&set.Spec.Template.Spec, func(name string) bool {
return strings.HasPrefix(name, controller.PumpMemberName(tc.Name))
})
// find an in-use configmap, will update it in-place
if inUseName != "" {
newCm.Name = inUseName
}
}
return pmm.typedControl.CreateOrUpdateConfigMap(tc, newCm)
}
func getNewPumpHeadlessService(tc *v1alpha1.TidbCluster) *corev1.Service {
if tc.Spec.Pump == nil {
return nil
}
objMeta, pumpLabel := getPumpMeta(tc, controller.PumpPeerMemberName)
return &corev1.Service{
ObjectMeta: objMeta,
Spec: corev1.ServiceSpec{
ClusterIP: "None",
Ports: []corev1.ServicePort{
{
Name: "pump",
Port: 8250,
TargetPort: intstr.FromInt(8250),
Protocol: corev1.ProtocolTCP,
},
},
Selector: pumpLabel,
PublishNotReadyAddresses: true,
},
}
}
// getNewPumpConfigMap returns a configMap for pump
func getNewPumpConfigMap(tc *v1alpha1.TidbCluster) (*corev1.ConfigMap, error) {
basePumpSpec, createPump := tc.BasePumpSpec()
if !createPump {
return nil, nil
}
spec := tc.Spec.Pump
objMeta, _ := getPumpMeta(tc, controller.PumpMemberName)
confText, err := MarshalTOML(spec.Config)
if err != nil {
return nil, err
}
name := controller.PumpMemberName(tc.Name)
data := map[string]string{
"pump-config": string(confText),
}
if basePumpSpec.ConfigUpdateStrategy() == v1alpha1.ConfigUpdateStrategyRollingUpdate {
sum, err := Sha256Sum(data)
if err != nil {
return nil, err
}
suffix := fmt.Sprintf("%x", sum)[0:7]
name = fmt.Sprintf("%s-%s", name, suffix)
}
objMeta.Name = name
return &corev1.ConfigMap{
ObjectMeta: objMeta,
Data: data,
}, nil
}
func getNewPumpStatefulSet(tc *v1alpha1.TidbCluster, cm *corev1.ConfigMap) (*appsv1.StatefulSet, error) {
spec, ok := tc.BasePumpSpec()
if !ok {
return nil, nil
}
objMeta, pumpLabel := getPumpMeta(tc, controller.PumpMemberName)
replicas := tc.Spec.Pump.Replicas
storageClass := tc.Spec.Pump.StorageClassName
podAnnos := CombineAnnotations(controller.AnnProm(8250), spec.Annotations())
storageRequest, err := controller.ParseStorageRequest(tc.Spec.Pump.Requests)
if err != nil {
return nil, fmt.Errorf("cannot parse storage request for pump, tidbcluster %s/%s, error: %v", tc.Namespace, tc.Name, err)
}
startScript, err := getPumpStartScript(tc)
if err != nil {
return nil, fmt.Errorf("cannot render start-script for pump, tidbcluster %s/%s, error: %v", tc.Namespace, tc.Name, err)
}
var envs []corev1.EnvVar
if tc.Spec.Pump.SetTimeZone != nil && *tc.Spec.Pump.SetTimeZone {
envs = append(envs, corev1.EnvVar{
Name: "TZ",
Value: tc.Spec.Timezone,
})
}
if spec.HostNetwork() {
// For backward compatibility, set HOSTNAME to POD_NAME in hostNetwork mode
envs = append(envs, corev1.EnvVar{
Name: "HOSTNAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "metadata.name",
},
},
})
}
containers := []corev1.Container{
{
Name: "pump",
Image: *tc.PumpImage(),
ImagePullPolicy: spec.ImagePullPolicy(),
Command: []string{
"/bin/sh",
"-c",
startScript,
},
Ports: []corev1.ContainerPort{{
Name: "pump",
ContainerPort: 8250,
}},
Resources: controller.ContainerResource(tc.Spec.Pump.ResourceRequirements),
Env: envs,
VolumeMounts: []corev1.VolumeMount{
{
Name: "data",
MountPath: "/data",
},
{
Name: "config",
MountPath: "/etc/pump",
},
},
},
}
// Keep backward compatibility for pump created by helm
volumes := []corev1.Volume{
{
Name: "config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: cm.Name,
},
Items: []corev1.KeyToPath{
{
Key: "pump-config",
Path: "pump.toml",
},
},
},
},
},
}
volumeClaims := []corev1.PersistentVolumeClaim{
{
ObjectMeta: metav1.ObjectMeta{
Name: "data",
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{
corev1.ReadWriteOnce,
},
StorageClassName: storageClass,
Resources: storageRequest,
},
},
}
podTemplate := corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: podAnnos,
Labels: pumpLabel,
},
Spec: corev1.PodSpec{
Containers: containers,
Volumes: volumes,
Affinity: spec.Affinity(),
Tolerations: spec.Tolerations(),
NodeSelector: spec.NodeSelector(),
SchedulerName: spec.SchedulerName(),
SecurityContext: spec.PodSecurityContext(),
HostNetwork: spec.HostNetwork(),
DNSPolicy: spec.DnsPolicy(),
},
}
return &appsv1.StatefulSet{
ObjectMeta: objMeta,
Spec: appsv1.StatefulSetSpec{
Selector: pumpLabel.LabelSelector(),
ServiceName: controller.PumpMemberName(tc.Name),
Replicas: &replicas,
Template: podTemplate,
VolumeClaimTemplates: volumeClaims,
},
}, nil
}
func getPumpMeta(tc *v1alpha1.TidbCluster, nameFunc func(string) string) (metav1.ObjectMeta, label.Label) {
instanceName := tc.GetInstanceName()
pumpLabel := label.New().Instance(instanceName).Pump()
objMeta := metav1.ObjectMeta{
Name: nameFunc(tc.Name),
Namespace: tc.Namespace,
Labels: pumpLabel,
OwnerReferences: []metav1.OwnerReference{controller.GetOwnerRef(tc)},
}
return objMeta, pumpLabel
}
func getPumpStartScript(tc *v1alpha1.TidbCluster) (string, error) {
// Keep the logic same as helm chart, but pump has not supported tls yet (no cert mounted)
// TODO: support tls
scheme := "http"
if tc.IsTLSClusterEnabled() {
scheme = "https"
}
return RenderPumpStartScript(&PumpStartScriptModel{
Scheme: scheme,
ClusterName: tc.Name,
LogLevel: getPumpLogLevel(tc),
})
}
func getPumpLogLevel(tc *v1alpha1.TidbCluster) string {
config := tc.Spec.Pump.Config
if config == nil {
return defaultPumpLogLevel
}
raw, ok := config["log-level"]
if !ok {
return defaultPumpLogLevel
}
logLevel, ok := raw.(string)
if !ok {
return defaultPumpLogLevel
}
return logLevel
}
func (pmm *pumpMemberManager) pumpStatefulSetIsUpgrading(set *apps.StatefulSet, tc *v1alpha1.TidbCluster) (bool, error) {
if statefulSetIsUpgrading(set) {
return true, nil
}
selector, err := label.New().
Instance(tc.GetInstanceName()).
Pump().
Selector()
if err != nil {
return false, err
}
pumpPods, err := pmm.podLister.Pods(tc.GetNamespace()).List(selector)
if err != nil {
return false, err
}
for _, pod := range pumpPods {
revisionHash, exist := pod.Labels[apps.ControllerRevisionHashLabelKey]
if !exist {
return false, nil
}
if revisionHash != tc.Status.Pump.StatefulSet.UpdateRevision {
return true, nil
}
}
return false, nil
}
type FakePumpMemberManager struct {
err error
}
func NewFakePumpMemberManager() *FakePumpMemberManager {
return &FakePumpMemberManager{}
}
func (ftmm *FakePumpMemberManager) SetSyncError(err error) {
ftmm.err = err
}
func (ftmm *FakePumpMemberManager) Sync(tc *v1alpha1.TidbCluster) error {
if ftmm.err != nil {
return ftmm.err
}
return nil
}