-
Notifications
You must be signed in to change notification settings - Fork 269
/
executor_manager.go
397 lines (343 loc) · 11.1 KB
/
executor_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
// 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 servermaster
import (
"context"
"sync"
"time"
"github.com/pingcap/log"
pb "github.com/pingcap/tiflow/engine/enginepb"
"github.com/pingcap/tiflow/engine/model"
"github.com/pingcap/tiflow/engine/pkg/notifier"
"github.com/pingcap/tiflow/engine/pkg/orm"
ormModel "github.com/pingcap/tiflow/engine/pkg/orm/model"
schedModel "github.com/pingcap/tiflow/engine/servermaster/scheduler/model"
"github.com/pingcap/tiflow/pkg/errors"
"github.com/pingcap/tiflow/pkg/label"
"go.uber.org/zap"
"golang.org/x/time/rate"
)
// ExecutorManager defines an interface to manager all executors
type ExecutorManager interface {
HandleHeartbeat(req *pb.HeartbeatRequest) (*pb.HeartbeatResponse, error)
AllocateNewExec(ctx context.Context, req *pb.RegisterExecutorRequest) (*ormModel.Executor, error)
// ExecutorCount returns executor count with given status
ExecutorCount(status model.ExecutorStatus) int
HasExecutor(executorID string) bool
ListExecutors() []*ormModel.Executor
GetAddr(executorID model.ExecutorID) (string, bool)
Run(ctx context.Context) error
// WatchExecutors returns a snapshot of all online executors plus
// a stream of events describing changes that happen to the executors
// after the snapshot is taken.
WatchExecutors(ctx context.Context) (
snap map[model.ExecutorID]string, stream *notifier.Receiver[model.ExecutorStatusChange], err error,
)
// GetExecutorInfos implements the interface scheduler.executorInfoProvider.
// It is called by the scheduler as the source of truth for executors.
GetExecutorInfos() map[model.ExecutorID]schedModel.ExecutorInfo
}
// ExecutorManagerImpl holds all the executors' info, including liveness, status, resource usage.
type ExecutorManagerImpl struct {
wg sync.WaitGroup
metaClient orm.Client
mu sync.Mutex
executors map[model.ExecutorID]*Executor
initHeartbeatTTL time.Duration
keepAliveInterval time.Duration
logRL *rate.Limiter
notifier *notifier.Notifier[model.ExecutorStatusChange]
}
// NewExecutorManagerImpl creates a new ExecutorManagerImpl instance
func NewExecutorManagerImpl(metaClient orm.Client, initHeartbeatTTL, keepAliveInterval time.Duration) *ExecutorManagerImpl {
return &ExecutorManagerImpl{
metaClient: metaClient,
executors: make(map[model.ExecutorID]*Executor),
initHeartbeatTTL: initHeartbeatTTL,
keepAliveInterval: keepAliveInterval,
logRL: rate.NewLimiter(rate.Every(time.Second*5), 1 /*burst*/),
notifier: notifier.NewNotifier[model.ExecutorStatusChange](),
}
}
// removeExecutorLocked removes an executor from the manager.
// Note that this method must be called with the lock held.
func (e *ExecutorManagerImpl) removeExecutorLocked(id model.ExecutorID) error {
log.Info("begin to remove executor", zap.String("id", string(id)))
exec, ok := e.executors[id]
if !ok {
// This executor has been removed
return errors.ErrUnknownExecutor.GenWithStackByArgs(id)
}
delete(e.executors, id)
log.Info("notify to offline exec")
e.notifier.Notify(model.ExecutorStatusChange{
ID: id,
Tp: model.EventExecutorOffline,
Addr: exec.Address,
})
// Delete the executor from the database. This operation may take a long time,
// and it may fail if the database is unavailable. So we don't want to hold the lock.
// Instead, we do the deletion in a goroutine.
//
// We use ttl mechanism to manage the executor's life cycle. So we can tolerate
// that a tombstone executor may be left in the database.
e.wg.Add(1)
go func() {
defer e.wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := e.metaClient.DeleteExecutor(ctx, id); err != nil {
log.Warn("failed to delete executor from database", zap.String("id", string(id)), zap.Error(err))
}
}()
return nil
}
// HandleHeartbeat implements pb interface,
func (e *ExecutorManagerImpl) HandleHeartbeat(req *pb.HeartbeatRequest) (*pb.HeartbeatResponse, error) {
if e.logRL.Allow() {
log.Info("handle heart beat", zap.Stringer("req", req))
}
e.mu.Lock()
execID := model.ExecutorID(req.ExecutorId)
exec, ok := e.executors[execID]
// executor not exists
if !ok {
e.mu.Unlock()
return nil, errors.ErrUnknownExecutor.GenWithStackByArgs(execID)
}
e.mu.Unlock()
if err := exec.heartbeat(req.Ttl); err != nil {
return nil, err
}
resp := &pb.HeartbeatResponse{}
return resp, nil
}
// registerExec registers executor to both executor manager and resource manager.
// Note that this method must be called with the lock held.
func (e *ExecutorManagerImpl) registerExecLocked(executorMeta *ormModel.Executor) {
log.Info("register executor", zap.Any("executor", executorMeta))
exec := &Executor{
Executor: *executorMeta,
lastUpdateTime: time.Now(),
heartbeatTTL: e.initHeartbeatTTL,
status: model.Initing,
logRL: rate.NewLimiter(rate.Every(time.Second*5), 1 /*burst*/),
}
e.executors[executorMeta.ID] = exec
e.notifier.Notify(model.ExecutorStatusChange{
ID: executorMeta.ID,
Tp: model.EventExecutorOnline,
Addr: executorMeta.Address,
})
}
// AllocateNewExec allocates new executor info to a give RegisterExecutorRequest
// and then registers the executor.
func (e *ExecutorManagerImpl) AllocateNewExec(ctx context.Context, req *pb.RegisterExecutorRequest) (*ormModel.Executor, error) {
pbExecutor := req.Executor
log.Info("allocate new executor", zap.Stringer("executor", pbExecutor))
e.mu.Lock()
var executorID model.ExecutorID
for {
executorID = model.ExecutorID(generateNodeID(pbExecutor.GetName()))
if _, ok := e.executors[executorID]; !ok {
break
}
}
labelSet, err := label.NewSetFromMap(req.GetExecutor().GetLabels())
if err != nil {
return nil, err
}
executorMeta := &ormModel.Executor{
ID: executorID,
Name: pbExecutor.GetName(),
Address: pbExecutor.GetAddress(),
Labels: ormModel.LabelSet(labelSet),
}
e.registerExecLocked(executorMeta)
e.mu.Unlock()
// Store the executor info to database.
// If any error occurs, client shouldn't use the executor.
// The executor in the map will be removed after the ttl expires.
if err := e.metaClient.CreateExecutor(ctx, executorMeta); err != nil {
return nil, errors.Trace(err)
}
return executorMeta, nil
}
// HasExecutor implements ExecutorManager.HasExecutor
func (e *ExecutorManagerImpl) HasExecutor(executorID string) bool {
e.mu.Lock()
defer e.mu.Unlock()
_, ok := e.executors[model.ExecutorID(executorID)]
return ok
}
// ListExecutors implements ExecutorManager.ListExecutors
func (e *ExecutorManagerImpl) ListExecutors() []*ormModel.Executor {
e.mu.Lock()
defer e.mu.Unlock()
ret := make([]*ormModel.Executor, 0, len(e.executors))
for _, exec := range e.executors {
execMeta := exec.Executor
ret = append(ret, &execMeta)
}
return ret
}
// Executor records the status of an executor instance.
type Executor struct {
ormModel.Executor
status model.ExecutorStatus
mu sync.RWMutex
// Last heartbeat
lastUpdateTime time.Time
heartbeatTTL time.Duration
logRL *rate.Limiter
}
func (e *Executor) checkAlive() bool {
if e.logRL.Allow() {
log.Info("check alive", zap.String("exec", string(e.ID)))
}
e.mu.Lock()
defer e.mu.Unlock()
if e.status == model.Tombstone {
return false
}
if e.lastUpdateTime.Add(e.heartbeatTTL).Before(time.Now()) {
e.status = model.Tombstone
return false
}
return true
}
func (e *Executor) heartbeat(ttl uint64) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.status == model.Tombstone {
return errors.ErrTombstoneExecutor.GenWithStackByArgs(e.ID)
}
e.lastUpdateTime = time.Now()
e.heartbeatTTL = time.Duration(ttl) * time.Millisecond
e.status = model.Running
return nil
}
func (e *Executor) statusEqual(status model.ExecutorStatus) bool {
e.mu.RLock()
defer e.mu.RUnlock()
return e.status == status
}
// Run implements ExecutorManager.Run
func (e *ExecutorManagerImpl) Run(ctx context.Context) error {
if err := e.resetExecutors(ctx); err != nil {
return errors.Errorf("failed to reset executors: %v", err)
}
ticker := time.NewTicker(e.keepAliveInterval)
defer func() {
ticker.Stop()
e.notifier.Close()
log.Info("executor manager exited")
}()
for {
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
case <-ticker.C:
err := e.checkAliveImpl()
if err != nil {
log.Info("check alive meet error", zap.Error(err))
}
}
}
}
func (e *ExecutorManagerImpl) checkAliveImpl() error {
e.mu.Lock()
defer e.mu.Unlock()
for id, exec := range e.executors {
if !exec.checkAlive() {
err := e.removeExecutorLocked(id)
return err
}
}
return nil
}
// ExecutorCount implements ExecutorManager.ExecutorCount
func (e *ExecutorManagerImpl) ExecutorCount(status model.ExecutorStatus) (count int) {
e.mu.Lock()
defer e.mu.Unlock()
for _, executor := range e.executors {
if executor.statusEqual(status) {
count++
}
}
return
}
// GetAddr implements ExecutorManager.GetAddr
func (e *ExecutorManagerImpl) GetAddr(executorID model.ExecutorID) (string, bool) {
e.mu.Lock()
defer e.mu.Unlock()
executor, exists := e.executors[executorID]
if !exists {
return "", false
}
return executor.Address, true
}
func (e *ExecutorManagerImpl) resetExecutors(ctx context.Context) error {
e.mu.Lock()
defer e.mu.Unlock()
orphanExecutorIDs := make(map[model.ExecutorID]struct{})
for id := range e.executors {
orphanExecutorIDs[id] = struct{}{}
}
executors, err := e.metaClient.QueryExecutors(ctx)
if err != nil {
return errors.Trace(err)
}
for _, executor := range executors {
e.registerExecLocked(executor)
delete(orphanExecutorIDs, executor.ID)
}
// Clean up executors that are not in the meta.
for id := range orphanExecutorIDs {
if err := e.removeExecutorLocked(id); err != nil {
return errors.Trace(err)
}
}
return nil
}
// WatchExecutors implements the ExecutorManager interface.
func (e *ExecutorManagerImpl) WatchExecutors(
ctx context.Context,
) (snap map[model.ExecutorID]string, receiver *notifier.Receiver[model.ExecutorStatusChange], err error) {
e.mu.Lock()
defer e.mu.Unlock()
snap = make(map[model.ExecutorID]string, len(e.executors))
for executorID, exec := range e.executors {
snap[executorID] = exec.Address
}
if err := e.notifier.Flush(ctx); err != nil {
return nil, nil, err
}
receiver = e.notifier.NewReceiver()
return
}
// GetExecutorInfos returns necessary information on the executor that
// is needed for scheduling.
func (e *ExecutorManagerImpl) GetExecutorInfos() map[model.ExecutorID]schedModel.ExecutorInfo {
e.mu.Lock()
defer e.mu.Unlock()
ret := make(map[model.ExecutorID]schedModel.ExecutorInfo, len(e.executors))
for id, exec := range e.executors {
schedInfo := schedModel.ExecutorInfo{
ID: id,
Labels: label.Set(exec.Labels),
}
ret[id] = schedInfo
}
return ret
}