-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
command.go
436 lines (378 loc) · 11.4 KB
/
command.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
// Copyright 2023 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/util/logutil"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/zap"
)
const (
ttlCmdKeyLeaseSeconds int64 = 60
ttlCmdKeyRequestPrefix = "/tidb/ttl/cmd/req/"
ttlCmdKeyResponsePrefix = "/tidb/ttl/cmd/resp/"
ttlCmdTypeTriggerTTLJob = "trigger_ttl_job"
)
// CmdRequest is the request for a TTL command
type CmdRequest struct {
RequestID string `json:"request_id"`
CmdType string `json:"cmd_type"`
Data json.RawMessage `json:"data"`
}
// GetTriggerTTLJobRequest returns the `TriggerNewTTLJobRequest` object if command type is 'trigger_ttl_job',
// otherwise, (nil, false) will be returned
func (r *CmdRequest) GetTriggerTTLJobRequest() (*TriggerNewTTLJobRequest, bool) {
if r.CmdType != ttlCmdTypeTriggerTTLJob {
return nil, false
}
var req TriggerNewTTLJobRequest
if err := json.Unmarshal(r.Data, &req); err != nil {
return nil, false
}
return &req, true
}
type cmdResponse struct {
RequestID string `json:"request_id"`
ErrorMessage string `json:"error_message"`
Data json.RawMessage `json:"data"`
}
// TriggerNewTTLJobRequest is the command detail to trigger a TTL job
type TriggerNewTTLJobRequest struct {
DBName string `json:"db_name"`
TableName string `json:"table_name"`
}
// TriggerNewTTLJobTableResult is the table detail of `TriggerNewTTLJobResponse`
type TriggerNewTTLJobTableResult struct {
TableID int64 `json:"table_id"`
DBName string `json:"db_name"`
TableName string `json:"table_name"`
PartitionName string `json:"partition_name,omitempty"`
JobID string `json:"job_id,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
// TriggerNewTTLJobResponse is the response detail for trigger_ttl_job command
type TriggerNewTTLJobResponse struct {
TableResult []*TriggerNewTTLJobTableResult `json:"table_result"`
}
// CommandClient is an interface used to send and response command of TTL jobs
type CommandClient interface {
// Command sends a command and waits for response. The first value of the return is the requestID, it always not empty.
Command(ctx context.Context, cmdType string, obj interface{}, response interface{}) (string, error)
// WatchCommand watches the commands that are sent
WatchCommand(ctx context.Context) <-chan *CmdRequest
// TakeCommand takes a command to ensure only one can handle the command.
// If the first return value is true, it means you have taken the command successfully,
// and you should call `ResponseCommand`
// after processed the command. Otherwise, you should not process this command because it is not belong to you.
TakeCommand(ctx context.Context, reqID string) (bool, error)
// ResponseCommand responses the result of the command. `TakeCommand` must be called first before `ResponseCommand`
// obj is the response object to the sender, if obj is an error, the sender will receive an error too.
ResponseCommand(ctx context.Context, reqID string, obj interface{}) error
}
// TriggerNewTTLJob triggers a new TTL job
func TriggerNewTTLJob(ctx context.Context, cli CommandClient, dbName, tableName string) (
*TriggerNewTTLJobResponse, error) {
var resp TriggerNewTTLJobResponse
_, err := cli.Command(ctx, ttlCmdTypeTriggerTTLJob, &TriggerNewTTLJobRequest{
DBName: dbName,
TableName: tableName,
}, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
// etcdClient is the client of etcd which implements the commandCli and notificationCli interface
type etcdClient struct {
etcdCli *clientv3.Client
}
// NewCommandClient creates a command client with etcd
func NewCommandClient(etcdCli *clientv3.Client) CommandClient {
return &etcdClient{
etcdCli: etcdCli,
}
}
func (c *etcdClient) sendCmd(ctx context.Context, cmdType string, obj interface{}) (string, error) {
reqID := uuid.New().String()
data, err := json.Marshal(obj)
if err != nil {
return reqID, err
}
requestJSON, err := json.Marshal(&CmdRequest{
RequestID: reqID,
CmdType: cmdType,
Data: data,
})
if err != nil {
return reqID, err
}
lease, err := c.etcdCli.Grant(ctx, ttlCmdKeyLeaseSeconds)
if err != nil {
return reqID, err
}
_, err = c.etcdCli.Put(ctx, ttlCmdKeyRequestPrefix+reqID, string(requestJSON), clientv3.WithLease(lease.ID))
if err != nil {
return reqID, err
}
return reqID, nil
}
func (c *etcdClient) waitCmdResponse(ctx context.Context, reqID string, obj interface{}) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(ttlCmdKeyLeaseSeconds))
defer cancel()
key := ttlCmdKeyResponsePrefix + reqID
ch := c.etcdCli.Watch(ctx, key)
ticker := time.NewTimer(time.Second)
defer ticker.Stop()
var respData []byte
loop:
for {
select {
case <-ticker.C:
response, err := c.etcdCli.Get(ctx, key)
if err != nil {
return err
}
if len(response.Kvs) > 0 {
respData = response.Kvs[0].Value
break loop
}
case resp := <-ch:
for _, event := range resp.Events {
if event.Type == clientv3.EventTypePut {
respData = event.Kv.Value
break loop
}
}
}
}
var cmdResp cmdResponse
if err := json.Unmarshal(respData, &cmdResp); err != nil {
return err
}
if cmdResp.ErrorMessage != "" {
return errors.New(cmdResp.ErrorMessage)
}
return json.Unmarshal(cmdResp.Data, obj)
}
// Command implements the CommandClient
func (c *etcdClient) Command(ctx context.Context, cmdType string, request interface{}, response interface{}) (
string, error) {
requestID, err := c.sendCmd(ctx, cmdType, request)
if err != nil {
return requestID, err
}
return requestID, c.waitCmdResponse(ctx, requestID, &response)
}
// TakeCommand implements the CommandClient
func (c *etcdClient) TakeCommand(ctx context.Context, reqID string) (bool, error) {
resp, err := c.etcdCli.Delete(ctx, ttlCmdKeyRequestPrefix+reqID)
if err != nil {
return false, err
}
return resp.Deleted > 0, nil
}
// ResponseCommand implements the CommandClient
func (c *etcdClient) ResponseCommand(ctx context.Context, reqID string, obj interface{}) error {
resp := &cmdResponse{
RequestID: reqID,
}
if err, ok := obj.(error); ok {
resp.ErrorMessage = err.Error()
} else {
data, err := json.Marshal(obj)
if err != nil {
return err
}
resp.Data = data
}
respJSON, err := json.Marshal(resp)
if err != nil {
return err
}
lease, err := c.etcdCli.Grant(ctx, ttlCmdKeyLeaseSeconds)
if err != nil {
return err
}
_, err = c.etcdCli.Put(ctx, ttlCmdKeyResponsePrefix+reqID, string(respJSON), clientv3.WithLease(lease.ID))
return err
}
// WatchCommand implements the CommandClient
func (c *etcdClient) WatchCommand(ctx context.Context) <-chan *CmdRequest {
ch := make(chan *CmdRequest)
go func() {
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
close(ch)
}()
etcdCh := c.etcdCli.Watch(ctx, ttlCmdKeyRequestPrefix, clientv3.WithPrefix())
for resp := range etcdCh {
for _, event := range resp.Events {
if event.Type != clientv3.EventTypePut {
continue
}
var request CmdRequest
if err := json.Unmarshal(event.Kv.Value, &request); err != nil {
logutil.BgLogger().Error(
"failed to parse ttl cmd payload",
zap.Error(err),
zap.ByteString("key", event.Kv.Key),
zap.ByteString("value", event.Kv.Value),
)
}
select {
case ch <- &request:
case <-ctx.Done():
return
}
}
}
}()
return ch
}
// mockClient is a mock implementation for CommandCli and NotificationCli
type mockClient struct {
sync.Mutex
store map[string]interface{}
commandWatchers []chan *CmdRequest
notificationWatchers map[string][]chan clientv3.WatchResponse
}
// NewMockCommandClient creates a mock command client
func NewMockCommandClient() CommandClient {
return &mockClient{
store: make(map[string]interface{}),
commandWatchers: make([]chan *CmdRequest, 0, 1),
notificationWatchers: make(map[string][]chan clientv3.WatchResponse),
}
}
// Command implements the CommandClient
func (c *mockClient) Command(ctx context.Context, cmdType string, request interface{}, response interface{}) (
string, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*time.Duration(ttlCmdKeyLeaseSeconds))
defer cancel()
reqID, err := c.sendCmd(ctx, cmdType, request)
if err != nil {
return reqID, err
}
responseKey := ttlCmdKeyResponsePrefix + reqID
for ctx.Err() == nil {
c.Lock()
val, ok := c.store[responseKey]
c.Unlock()
if !ok {
continue
}
res, ok := val.(*cmdResponse)
if !ok {
return reqID, errors.New("response cannot be casted to *cmdResponse")
}
if res.ErrorMessage != "" {
return reqID, errors.New(res.ErrorMessage)
}
if err = json.Unmarshal(res.Data, response); err != nil {
return reqID, err
}
return reqID, nil
}
return reqID, ctx.Err()
}
func (c *mockClient) sendCmd(ctx context.Context, cmdType string, request interface{}) (string, error) {
reqID := uuid.New().String()
data, err := json.Marshal(request)
if err != nil {
return reqID, err
}
req := &CmdRequest{
RequestID: reqID,
CmdType: cmdType,
Data: data,
}
c.Lock()
defer c.Unlock()
key := ttlCmdKeyRequestPrefix + reqID
c.store[key] = req
for _, ch := range c.commandWatchers {
select {
case <-ctx.Done():
return reqID, ctx.Err()
case ch <- req:
default:
return reqID, errors.New("watcher channel is blocked")
}
}
return reqID, nil
}
// TakeCommand implements the CommandClient
func (c *mockClient) TakeCommand(_ context.Context, reqID string) (bool, error) {
c.Lock()
defer c.Unlock()
key := ttlCmdKeyRequestPrefix + reqID
if _, ok := c.store[key]; ok {
delete(c.store, key)
return true, nil
}
return false, nil
}
// ResponseCommand implements the CommandClient
func (c *mockClient) ResponseCommand(_ context.Context, reqID string, obj interface{}) error {
c.Lock()
defer c.Unlock()
resp := &cmdResponse{
RequestID: reqID,
}
if respErr, ok := obj.(error); ok {
resp.ErrorMessage = respErr.Error()
} else {
jsonData, err := json.Marshal(obj)
if err != nil {
return err
}
resp.Data = jsonData
}
c.store[ttlCmdKeyResponsePrefix+reqID] = resp
return nil
}
// WatchCommand implements the CommandClient
func (c *mockClient) WatchCommand(ctx context.Context) <-chan *CmdRequest {
c.Lock()
defer c.Unlock()
ch := make(chan *CmdRequest, 16+len(c.store))
c.commandWatchers = append(c.commandWatchers, ch)
for key, val := range c.store {
if strings.HasPrefix(key, ttlCmdKeyRequestPrefix) {
if req, ok := val.(*CmdRequest); ok {
ch <- req
}
}
}
go func() {
<-ctx.Done()
c.Lock()
defer c.Unlock()
for i, chItem := range c.commandWatchers {
if chItem == ch {
c.commandWatchers = append(c.commandWatchers[:i], c.commandWatchers[i+1:]...)
break
}
}
close(ch)
}()
return ch
}