forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_server.go
217 lines (200 loc) · 6.96 KB
/
rpc_server.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
// 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 server
import (
"context"
"fmt"
"net"
"github.com/pingcap/kvproto/pkg/coprocessor"
"github.com/pingcap/kvproto/pkg/diagnosticspb"
"github.com/pingcap/kvproto/pkg/tikvpb"
"github.com/pingcap/sysutil"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/privilege/privileges"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/store/mockstore/mocktikv"
"github.com/pingcap/tidb/store/mockstore/unistore"
"github.com/pingcap/tidb/store/tikv"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/memory"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
)
// NewRPCServer creates a new rpc server.
func NewRPCServer(config *config.Config, dom *domain.Domain, sm util.SessionManager) *grpc.Server {
defer func() {
if v := recover(); v != nil {
logutil.BgLogger().Error("panic in TiDB RPC server", zap.Reflect("r", v),
zap.Stack("stack trace"))
}
}()
s := grpc.NewServer()
rpcSrv := &rpcServer{
DiagnosticsServer: sysutil.NewDiagnosticsServer(config.Log.File.Filename),
dom: dom,
sm: sm,
}
// For redirection the cop task.
mocktikv.GRPCClientFactory = func() mocktikv.Client {
return tikv.NewTestRPCClient(config.Security.ClusterSecurity())
}
unistore.GRPCClientFactory = func() unistore.Client {
return tikv.NewTestRPCClient(config.Security.ClusterSecurity())
}
diagnosticspb.RegisterDiagnosticsServer(s, rpcSrv)
tikvpb.RegisterTikvServer(s, rpcSrv)
return s
}
// rpcServer contains below 2 services:
// 1. Diagnose service, it's used for SQL diagnose.
// 2. Coprocessor service, it reuse the TikvServer interface, but only support the Coprocessor interface now.
// Coprocessor service will handle the cop task from other TiDB server. Currently, it's only use for read the cluster memory table.
type rpcServer struct {
*sysutil.DiagnosticsServer
tikvpb.TikvServer
dom *domain.Domain
sm util.SessionManager
}
// Coprocessor implements the TiKVServer interface.
func (s *rpcServer) Coprocessor(ctx context.Context, in *coprocessor.Request) (resp *coprocessor.Response, err error) {
resp = &coprocessor.Response{}
defer func() {
if v := recover(); v != nil {
logutil.BgLogger().Error("panic when RPC server handing coprocessor", zap.Reflect("r", v),
zap.Stack("stack trace"))
resp.OtherError = fmt.Sprintf("panic when RPC server handing coprocessor, stack:%v", v)
}
}()
resp = s.handleCopRequest(ctx, in)
return resp, nil
}
// CoprocessorStream implements the TiKVServer interface.
func (s *rpcServer) CoprocessorStream(in *coprocessor.Request, stream tikvpb.Tikv_CoprocessorStreamServer) (err error) {
resp := &coprocessor.Response{}
defer func() {
if v := recover(); v != nil {
logutil.BgLogger().Error("panic when RPC server handing coprocessor stream", zap.Reflect("r", v),
zap.Stack("stack trace"))
resp.OtherError = fmt.Sprintf("panic when when RPC server handing coprocessor stream, stack:%v", v)
err = stream.Send(resp)
if err != nil {
logutil.BgLogger().Error("panic when RPC server handing coprocessor stream, send response to stream error", zap.Error(err))
}
}
}()
se, err := s.createSession()
if err != nil {
resp.OtherError = err.Error()
return stream.Send(resp)
}
defer se.Close()
h := executor.NewCoprocessorDAGHandler(se)
return h.HandleStreamRequest(context.Background(), in, stream)
}
// BatchCommands implements the TiKVServer interface.
func (s *rpcServer) BatchCommands(ss tikvpb.Tikv_BatchCommandsServer) error {
defer func() {
if v := recover(); v != nil {
logutil.BgLogger().Error("panic when RPC server handing batch commands", zap.Reflect("r", v),
zap.Stack("stack trace"))
}
}()
for {
reqs, err := ss.Recv()
if err != nil {
logutil.BgLogger().Error("RPC server batch commands receive fail", zap.Error(err))
return err
}
responses := make([]*tikvpb.BatchCommandsResponse_Response, 0, len(reqs.Requests))
for _, req := range reqs.Requests {
var response *tikvpb.BatchCommandsResponse_Response
switch request := req.Cmd.(type) {
case *tikvpb.BatchCommandsRequest_Request_Coprocessor:
cop := request.Coprocessor
resp, err := s.Coprocessor(context.Background(), cop)
if err != nil {
return err
}
response = &tikvpb.BatchCommandsResponse_Response{
Cmd: &tikvpb.BatchCommandsResponse_Response_Coprocessor{
Coprocessor: resp,
},
}
case *tikvpb.BatchCommandsRequest_Request_Empty:
response = &tikvpb.BatchCommandsResponse_Response{
Cmd: &tikvpb.BatchCommandsResponse_Response_Empty{
Empty: &tikvpb.BatchCommandsEmptyResponse{
TestId: request.Empty.TestId,
},
},
}
default:
logutil.BgLogger().Info("RPC server batch commands receive unknown request", zap.Any("req", request))
response = &tikvpb.BatchCommandsResponse_Response{
Cmd: &tikvpb.BatchCommandsResponse_Response_Empty{
Empty: &tikvpb.BatchCommandsEmptyResponse{},
},
}
}
responses = append(responses, response)
}
err = ss.Send(&tikvpb.BatchCommandsResponse{
Responses: responses,
RequestIds: reqs.GetRequestIds(),
})
if err != nil {
logutil.BgLogger().Error("RPC server batch commands send fail", zap.Error(err))
return err
}
}
}
// handleCopRequest handles the cop dag request.
func (s *rpcServer) handleCopRequest(ctx context.Context, req *coprocessor.Request) *coprocessor.Response {
resp := &coprocessor.Response{}
se, err := s.createSession()
if err != nil {
resp.OtherError = err.Error()
return resp
}
defer se.Close()
if p, ok := peer.FromContext(ctx); ok {
se.GetSessionVars().SourceAddr = *p.Addr.(*net.TCPAddr)
}
h := executor.NewCoprocessorDAGHandler(se)
return h.HandleRequest(ctx, req)
}
func (s *rpcServer) createSession() (session.Session, error) {
se, err := session.CreateSessionWithDomain(s.dom.Store(), s.dom)
if err != nil {
return nil, err
}
do := domain.GetDomain(se)
is := do.InfoSchema()
pm := &privileges.UserPrivileges{
Handle: do.PrivilegeHandle(),
}
privilege.BindPrivilegeManager(se, pm)
se.GetSessionVars().TxnCtx.InfoSchema = is
// This is for disable parallel hash agg.
// TODO: remove this.
se.GetSessionVars().SetHashAggPartialConcurrency(1)
se.GetSessionVars().SetHashAggFinalConcurrency(1)
se.GetSessionVars().StmtCtx.MemTracker = memory.NewTracker(memory.LabelForCoprocessor, -1)
se.SetSessionManager(s.sm)
return se, nil
}