/
pvc_modifier.go
310 lines (254 loc) · 9.15 KB
/
pvc_modifier.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
// Copyright 2022 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 volumes
import (
"context"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
errutil "k8s.io/apimachinery/pkg/util/errors"
klog "k8s.io/klog/v2"
"github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
"github.com/pingcap/tidb-operator/pkg/controller"
"github.com/pingcap/tidb-operator/pkg/manager/utils"
)
const (
annoKeyPVCSpecRevision = "spec.tidb.pingcap.com/revision"
annoKeyPVCSpecStorageClass = "spec.tidb.pingcap.com/storage-class"
annoKeyPVCSpecStorageSize = "spec.tidb.pingcap.com/storage-size"
annoKeyPVCStatusRevision = "status.tidb.pingcap.com/revision"
annoKeyPVCStatusStorageClass = "status.tidb.pingcap.com/storage-class"
annoKeyPVCStatusStorageSize = "status.tidb.pingcap.com/storage-size"
annoKeyPVCLastTransitionTimestamp = "status.tidb.pingcap.com/last-transition-timestamp"
defaultModifyWaitingDuration = time.Minute * 1
)
type PVCModifierInterface interface {
Sync(tc *v1alpha1.TidbCluster) error
}
type pvcModifier struct {
deps *controller.Dependencies
pm PodVolumeModifier
utils *volCompareUtils
}
func NewPVCModifier(deps *controller.Dependencies) PVCModifierInterface {
return &pvcModifier{
deps: deps,
pm: NewPodVolumeModifier(deps),
utils: newVolCompareUtils(deps),
}
}
func (p *pvcModifier) Sync(tc *v1alpha1.TidbCluster) error {
components := tc.AllComponentStatus()
errs := []error{}
for _, comp := range components {
ctx, err := p.utils.BuildContextForTC(tc, comp)
if err != nil {
errs = append(errs, fmt.Errorf("build ctx used by modifier for %s/%s:%s failed: %w", tc.Namespace, tc.Name, comp.MemberType(), err))
continue
}
err = p.modifyVolumes(ctx)
if err != nil {
errs = append(errs, fmt.Errorf("modify volumes for %s failed: %w", ctx.ComponentID(), err))
continue
}
}
return errutil.NewAggregate(errs)
}
func (p *pvcModifier) modifyVolumes(ctx *componentVolumeContext) error {
if ctx.status.GetPhase() != v1alpha1.NormalPhase {
return fmt.Errorf("component phase is not Normal")
}
if err := p.tryToRecreateSTS(ctx); err != nil {
return err
}
if err := p.tryToModifyPVC(ctx); err != nil {
return err
}
return nil
}
func (p *pvcModifier) tryToRecreateSTS(ctx *componentVolumeContext) error {
ns := ctx.sts.Namespace
name := ctx.sts.Name
// Modifier does not support new volumes, trigger error if so and return.
isSynced, err := p.utils.IsStatefulSetSynced(ctx, ctx.sts)
if err != nil {
return fmt.Errorf("change in number of volumes is not supported. For pd, tikv, tidb supported with VolumeReplacing feature. Reconciliation is blocked due to : %s", err.Error())
}
if isSynced {
return nil
}
if utils.StatefulSetIsUpgrading(ctx.sts) {
return fmt.Errorf("component sts %s/%s is upgrading", ctx.sts.Name, ctx.sts.Namespace)
}
if err := utils.DeleteStatefulSetWithOrphan(ctx, p.deps.StatefulSetControl, p.deps.TiDBClusterControl, ctx.tc, ctx.sts); err != nil {
return fmt.Errorf("delete sts %s/%s for component %s failed: %s", ns, name, ctx.ComponentID(), err)
}
klog.Infof("recreate statefulset %s/%s for component %s", ns, name, ctx.ComponentID())
// component manager will create the sts in next reconciliation
return nil
}
func (p *pvcModifier) tryToModifyPVC(ctx *componentVolumeContext) error {
for _, pod := range ctx.pods {
actual, err := p.pm.GetActualVolumes(pod, ctx.desiredVolumes)
if err != nil {
return err
}
isNeed := p.pm.ShouldModify(actual)
if ctx.shouldEvict {
// ensure leader eviction is finished and tikv store is up
if !isNeed {
if err := p.endEvictLeader(ctx.tc, pod); err != nil {
return err
}
if !isTiKVStoreUp(ctx.tc, pod) {
return fmt.Errorf("wait for tikv store %s/%s up", pod.Namespace, pod.Name)
}
continue
}
// try to evict leader if need to modify
isEvicted := isLeaderEvictedOrTimeout(ctx.tc, pod)
if !isEvicted {
// do not evict leader when resizing PVC (increasing size)
// as if the storage size is not enough, the leader eviction will be blocked (never finished)
if !skipEvictLeaderForSizeModify(actual) {
if ensureTiKVLeaderEvictionCondition(ctx.tc, metav1.ConditionTrue) {
// return to sync tc
return fmt.Errorf("try to evict leader for tidbcluster %s/%s", ctx.tc.Namespace, ctx.tc.Name)
}
if err := p.evictLeader(ctx.tc, pod); err != nil {
return err
}
return fmt.Errorf("wait for leader eviction of %s/%s completed", pod.Namespace, pod.Name)
} else {
klog.Infof("skip evicting leader for %s/%s as the storage size is changing", pod.Namespace, pod.Name)
}
}
}
if !isNeed {
continue
}
if err := p.pm.Modify(actual); err != nil {
return err
}
}
if ctx.shouldEvict {
if ensureTiKVLeaderEvictionCondition(ctx.tc, metav1.ConditionFalse) {
// return to sync tc
return fmt.Errorf("try to stop evicting leader for tidbcluster %s/%s", ctx.tc.Namespace, ctx.tc.Name)
}
}
return nil
}
// skip evict leader if the storage size should be modified or is in modifying phase
func skipEvictLeaderForSizeModify(actual []ActualVolume) bool {
for _, vol := range actual {
if vol.PVC == nil || vol.Desired == nil {
continue
}
annoStatusSize, ok := vol.PVC.Annotations[annoKeyPVCStatusStorageSize]
if ok {
// modified by the PVC Modifier before (with status size annotation)
if annoStatusSize == vol.Desired.Size.String() {
continue // already up to date, no need to modify size
}
return true // need to modify size
}
// not modified by the PVC modifier before (without status size annotation)
quantity := vol.GetStorageSize()
statusSize := quantity.String()
if statusSize == vol.Desired.Size.String() {
// special case: skip evict leader (again) as the PVC is in modfiying phase (and the status size annotation is not set yet)
if vol.Phase == VolumePhaseModifying {
return true
}
// already modified, in fact, the status size annotation should already be set
continue
}
// need to modify size
return true
}
return false
}
func ensureTiKVLeaderEvictionCondition(tc *v1alpha1.TidbCluster, status metav1.ConditionStatus) bool {
if meta.IsStatusConditionPresentAndEqual(tc.Status.TiKV.Conditions, v1alpha1.ConditionTypeLeaderEvicting, status) {
return false
}
var reason, message string
switch status {
case metav1.ConditionTrue:
reason = "ModifyVolume"
message = "Evicting leader for volume modification"
case metav1.ConditionFalse:
reason = "NoLeaderEviction"
message = "Leader can be scheduled to all nodes"
case metav1.ConditionUnknown:
reason = "Unknown"
message = "Leader eviction status is unknown"
}
cond := metav1.Condition{
Type: v1alpha1.ConditionTypeLeaderEvicting,
Status: status,
Reason: reason,
Message: message,
}
meta.SetStatusCondition(&tc.Status.TiKV.Conditions, cond)
return true
}
func isTiKVStoreUp(tc *v1alpha1.TidbCluster, pod *corev1.Pod) bool {
// wait store to be Up
for _, store := range tc.Status.TiKV.Stores {
if store.PodName == pod.Name && store.State != v1alpha1.TiKVStateUp {
return false
}
}
return true
}
func isLeaderEvictionFinished(tc *v1alpha1.TidbCluster, pod *corev1.Pod) bool {
if _, exist := tc.Status.TiKV.EvictLeader[pod.Name]; exist {
return false
}
return true
}
func isLeaderEvicting(pod *corev1.Pod) bool {
_, exist := pod.Annotations[v1alpha1.EvictLeaderAnnKeyForResize]
return exist
}
func (p *pvcModifier) evictLeader(tc *v1alpha1.TidbCluster, pod *corev1.Pod) error {
if isLeaderEvicting(pod) {
return nil
}
pod = pod.DeepCopy()
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[v1alpha1.EvictLeaderAnnKeyForResize] = v1alpha1.EvictLeaderValueNone
if _, err := p.deps.KubeClientset.CoreV1().Pods(pod.Namespace).Update(context.TODO(), pod, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("add leader eviction annotation to pod %s/%s failed: %s", pod.Namespace, pod.Name, err)
}
return nil
}
func (p *pvcModifier) endEvictLeader(tc *v1alpha1.TidbCluster, pod *corev1.Pod) error {
if isLeaderEvicting(pod) {
pod = pod.DeepCopy()
delete(pod.Annotations, v1alpha1.EvictLeaderAnnKeyForResize)
if _, err := p.deps.KubeClientset.CoreV1().Pods(pod.Namespace).Update(context.TODO(), pod, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("delete leader eviction annotation to pod %s/%s failed: %s", pod.Namespace, pod.Name, err)
}
// Return an error once after deleting annotation, to give pod_control a chance to stop the eviction.
// (but do not block / re-check in case the eviction here maybe manually requested by user via annotation)
return fmt.Errorf("wait for leader eviction of %s/%s finished", pod.Namespace, pod.Name)
}
return nil
}