-
Notifications
You must be signed in to change notification settings - Fork 269
/
manager.go
371 lines (343 loc) · 11.2 KB
/
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
// Copyright 2021 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 processor
import (
"context"
"fmt"
"io"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/log"
"github.com/pingcap/tiflow/cdc/model"
"github.com/pingcap/tiflow/cdc/vars"
"github.com/pingcap/tiflow/pkg/config"
cerror "github.com/pingcap/tiflow/pkg/errors"
"github.com/pingcap/tiflow/pkg/etcd"
"github.com/pingcap/tiflow/pkg/orchestrator"
"github.com/pingcap/tiflow/pkg/upstream"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
)
type commandTp int
const (
commandTpUnknown commandTp = iota
commandTpWriteDebugInfo
processorLogsWarnDuration = 1 * time.Second
)
type command struct {
tp commandTp
payload interface{}
done chan<- error
}
// Manager is a manager of processor, which maintains the state and behavior of processors
type Manager interface {
orchestrator.Reactor
// Close the manager itself and all processors. Can't be called with `Tick` concurrently.
// After it's called, all other methods shouldn't be called any more.
Close()
WriteDebugInfo(ctx context.Context, w io.Writer, done chan<- error)
}
// managerImpl is a manager of processor, which maintains the state and behavior of processors
type managerImpl struct {
captureInfo *model.CaptureInfo
liveness *model.Liveness
processors map[model.ChangeFeedID]*processor
commandQueue chan *command
upstreamManager *upstream.Manager
newProcessor func(
*model.ChangeFeedInfo,
*model.ChangeFeedStatus,
*model.CaptureInfo,
model.ChangeFeedID,
*upstream.Upstream,
*model.Liveness,
uint64,
*config.SchedulerConfig,
etcd.OwnerCaptureInfoClient,
*vars.GlobalVars,
) *processor
cfg *config.SchedulerConfig
globalVars *vars.GlobalVars
metricProcessorCloseDuration prometheus.Observer
}
// NewManager creates a new processor manager
func NewManager(
captureInfo *model.CaptureInfo,
upstreamManager *upstream.Manager,
liveness *model.Liveness,
cfg *config.SchedulerConfig,
globalVars *vars.GlobalVars,
) Manager {
return &managerImpl{
captureInfo: captureInfo,
liveness: liveness,
processors: make(map[model.ChangeFeedID]*processor),
commandQueue: make(chan *command, 4),
upstreamManager: upstreamManager,
newProcessor: NewProcessor,
metricProcessorCloseDuration: processorCloseDuration,
cfg: cfg,
globalVars: globalVars,
}
}
// Tick implements the `orchestrator.State` interface
// the `state` parameter is sent by the etcd worker, the `state` must be a snapshot of KVs in etcd
// the Tick function of Manager create or remove processor instances according to the specified `state`, or pass the `state` to processor instances
func (m *managerImpl) Tick(stdCtx context.Context, state orchestrator.ReactorState) (nextState orchestrator.ReactorState, err error) {
globalState := state.(*orchestrator.GlobalReactorState)
m.handleCommand()
var inactiveChangefeedCount int
for changefeedID, changefeedState := range globalState.Changefeeds {
if !changefeedState.Active(m.captureInfo.ID) {
inactiveChangefeedCount++
m.closeProcessor(changefeedID)
continue
}
currentChangefeedEpoch := changefeedState.Info.Epoch
p, exist := m.processors[changefeedID]
if !exist {
up, ok := m.upstreamManager.Get(changefeedState.Info.UpstreamID)
if !ok {
upstreamInfo := globalState.Upstreams[changefeedState.Info.UpstreamID]
up = m.upstreamManager.AddUpstream(upstreamInfo)
}
failpoint.Inject("processorManagerHandleNewChangefeedDelay", nil)
cfg := *m.cfg
cfg.ChangefeedSettings = changefeedState.Info.Config.Scheduler
p = m.newProcessor(
changefeedState.Info, changefeedState.Status,
m.captureInfo, changefeedID, up, m.liveness,
currentChangefeedEpoch, &cfg, m.globalVars.EtcdClient,
m.globalVars)
m.processors[changefeedID] = p
}
if currentChangefeedEpoch != p.changefeedEpoch {
// Changefeed has restarted due to error, the processor is stale.
m.closeProcessor(changefeedID)
continue
}
// check if the changefeed is normal before tick
if !checkChangefeedNormal(changefeedState) {
patchProcessorErr(p.captureInfo, changefeedState,
cerror.ErrAdminStopProcessor.GenWithStackByArgs())
m.closeProcessor(changefeedID)
continue
}
// check the capture is alive
changefeedState.CheckCaptureAlive(p.captureInfo.ID)
// check if the task position is created
if createTaskPosition(changefeedState, p.captureInfo) {
continue
}
err, warning := p.Tick(stdCtx, changefeedState.Info, changefeedState.Status)
if warning != nil {
patchProcessorWarning(p.captureInfo, changefeedState, warning)
}
if err != nil {
patchProcessorErr(p.captureInfo, changefeedState, err)
// patchProcessorErr have already patched its error to tell the owner
// manager can just close the processor and continue to tick other processors
m.closeProcessor(changefeedID)
}
}
// check if the processors in memory is leaked
if len(globalState.Changefeeds)-inactiveChangefeedCount != len(m.processors) {
for changefeedID := range m.processors {
if _, exist := globalState.Changefeeds[changefeedID]; !exist {
m.closeProcessor(changefeedID)
}
}
}
if err := m.upstreamManager.Tick(stdCtx, globalState); err != nil {
return state, errors.Trace(err)
}
return state, nil
}
// checkChangefeedNormal checks if the changefeed is runnable.
func checkChangefeedNormal(changefeed *orchestrator.ChangefeedReactorState) bool {
// check the state in this tick, make sure that the admin job type of the changefeed is not stopped
if changefeed.Info.AdminJobType.IsStopState() || changefeed.Status.AdminJobType.IsStopState() {
return false
}
// add a patch to check the changefeed is runnable when applying the patches in the etcd worker.
changefeed.CheckChangefeedNormal()
return true
}
// createTaskPosition will create a new task position if a task position does not exist.
// task position not exist only when the processor is running first in the first tick.
func createTaskPosition(changefeed *orchestrator.ChangefeedReactorState,
captureInfo *model.CaptureInfo,
) (skipThisTick bool) {
if _, exist := changefeed.TaskPositions[captureInfo.ID]; exist {
return false
}
changefeed.PatchTaskPosition(captureInfo.ID,
func(position *model.TaskPosition) (*model.TaskPosition, bool, error) {
if position == nil {
return &model.TaskPosition{}, true, nil
}
return position, false, nil
})
return true
}
func patchProcessorErr(captureInfo *model.CaptureInfo,
changefeed *orchestrator.ChangefeedReactorState,
err error,
) {
if isProcessorIgnorableError(err) {
log.Info("processor exited",
zap.String("capture", captureInfo.ID),
zap.String("namespace", changefeed.ID.Namespace),
zap.String("changefeed", changefeed.ID.ID),
zap.Error(err))
return
}
// record error information in etcd
var code string
if rfcCode, ok := cerror.RFCCode(err); ok {
code = string(rfcCode)
} else {
code = string(cerror.ErrProcessorUnknown.RFCCode())
}
changefeed.PatchTaskPosition(captureInfo.ID,
func(position *model.TaskPosition) (*model.TaskPosition, bool, error) {
if position == nil {
position = &model.TaskPosition{}
}
position.Error = &model.RunningError{
Time: time.Now(),
Addr: captureInfo.AdvertiseAddr,
Code: code,
Message: err.Error(),
}
return position, true, nil
})
log.Error("run processor failed",
zap.String("capture", captureInfo.ID),
zap.String("namespace", changefeed.ID.Namespace),
zap.String("changefeed", changefeed.ID.ID),
zap.Error(err))
}
func patchProcessorWarning(captureInfo *model.CaptureInfo,
changefeed *orchestrator.ChangefeedReactorState, err error,
) {
if err == nil {
return
}
var code string
if rfcCode, ok := cerror.RFCCode(err); ok {
code = string(rfcCode)
} else {
code = string(cerror.ErrProcessorUnknown.RFCCode())
}
changefeed.PatchTaskPosition(captureInfo.ID,
func(position *model.TaskPosition) (*model.TaskPosition, bool, error) {
if position == nil {
position = &model.TaskPosition{}
}
position.Warning = &model.RunningError{
Time: time.Now(),
Addr: captureInfo.AdvertiseAddr,
Code: code,
Message: err.Error(),
}
return position, true, nil
})
}
func (m *managerImpl) closeProcessor(changefeedID model.ChangeFeedID) {
processor, exist := m.processors[changefeedID]
if exist {
startTime := time.Now()
err := processor.Close()
costTime := time.Since(startTime)
if costTime > processorLogsWarnDuration {
log.Warn("processor close took too long",
zap.String("namespace", changefeedID.Namespace),
zap.String("changefeed", changefeedID.ID),
zap.String("capture", m.captureInfo.ID),
zap.Duration("duration", costTime))
}
m.metricProcessorCloseDuration.Observe(costTime.Seconds())
if err != nil {
log.Warn("failed to close processor",
zap.String("namespace", changefeedID.Namespace),
zap.String("changefeed", changefeedID.ID),
zap.Error(err))
}
delete(m.processors, changefeedID)
}
}
// Close the manager itself and all processors.
// Note: This method must not be called with `Tick`. Please be careful.
func (m *managerImpl) Close() {
log.Info("processor.Manager is closing")
for changefeedID := range m.processors {
m.closeProcessor(changefeedID)
}
// FIXME: we should drain command queue and signal callers an error.
}
// WriteDebugInfo write the debug info to Writer
func (m *managerImpl) WriteDebugInfo(
ctx context.Context, w io.Writer, done chan<- error,
) {
err := m.sendCommand(ctx, commandTpWriteDebugInfo, w, done)
if err != nil {
log.Warn("send command commandTpWriteDebugInfo failed", zap.Error(err))
}
}
// sendCommands sends command to manager.
// `done` is closed upon command completion or sendCommand returns error.
func (m *managerImpl) sendCommand(
ctx context.Context, tp commandTp, payload interface{}, done chan<- error,
) error {
cmd := &command{tp: tp, payload: payload, done: done}
select {
case <-ctx.Done():
close(done)
return errors.Trace(ctx.Err())
case m.commandQueue <- cmd:
// FIXME: signal EtcdWorker to handle commands ASAP.
}
return nil
}
func (m *managerImpl) handleCommand() {
var cmd *command
select {
case cmd = <-m.commandQueue:
default:
return
}
defer close(cmd.done)
switch cmd.tp {
case commandTpWriteDebugInfo:
w := cmd.payload.(io.Writer)
err := m.writeDebugInfo(w)
if err != nil {
cmd.done <- err
}
default:
log.Warn("Unknown command in processor manager", zap.Any("command", cmd))
}
}
func (m *managerImpl) writeDebugInfo(w io.Writer) error {
for changefeedID, processor := range m.processors {
fmt.Fprintf(w, "changefeedID: %s\n", changefeedID)
err := processor.WriteDebugInfo(w)
if err != nil {
return errors.Trace(err)
}
fmt.Fprintf(w, "\n")
}
return nil
}