/
rpc_server.go
393 lines (361 loc) · 11 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
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
// Copyright 2014 mqant Author. All Rights Reserved.
//
// 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 defaultrpc
import (
"fmt"
"github.com/liangdas/mqant/conf"
"github.com/liangdas/mqant/gate"
"github.com/liangdas/mqant/log"
"github.com/liangdas/mqant/module"
"github.com/liangdas/mqant/rpc"
"github.com/liangdas/mqant/rpc/pb"
"github.com/liangdas/mqant/rpc/util"
opentracing "github.com/opentracing/opentracing-go"
"reflect"
"runtime"
"sync"
"time"
)
type RPCServer struct {
module module.Module
app module.App
functions map[string]mqrpc.FunctionInfo
remote_server *AMQPServer
local_server *LocalServer
redis_server *RedisServer
mq_chan chan mqrpc.CallInfo //接收到请求信息的队列
callback_chan chan mqrpc.CallInfo //信息处理完成的队列
wg sync.WaitGroup //任务阻塞
call_chan_done chan error
listener mqrpc.RPCListener
executing int64 //正在执行的goroutine数量
}
func NewRPCServer(app module.App, module module.Module) (mqrpc.RPCServer, error) {
rpc_server := new(RPCServer)
rpc_server.app = app
rpc_server.module = module
rpc_server.call_chan_done = make(chan error)
rpc_server.functions = make(map[string]mqrpc.FunctionInfo)
rpc_server.mq_chan = make(chan mqrpc.CallInfo)
rpc_server.callback_chan = make(chan mqrpc.CallInfo, 50)
//先创建一个本地的RPC服务
local_server, err := NewLocalServer(rpc_server.mq_chan)
if err != nil {
log.Error("LocalServer Dial: %s", err)
}
rpc_server.local_server = local_server
go rpc_server.on_call_handle(rpc_server.mq_chan, rpc_server.callback_chan, rpc_server.call_chan_done)
go rpc_server.on_callback_handle(rpc_server.callback_chan) //结果发送队列
return rpc_server, nil
}
/**
创建一个支持远程RPC的服务
*/
func (s *RPCServer) NewRabbitmqRPCServer(info *conf.Rabbitmq) (err error) {
remote_server, err := NewAMQPServer(info, s.mq_chan)
if err != nil {
log.Error("AMQPServer Dial: %s", err)
}
s.remote_server = remote_server
return
}
/**
创建一个支持远程Redis RPC的服务
*/
func (s *RPCServer) NewRedisRPCServer(info *conf.Redis) (err error) {
redis_server, err := NewRedisServer(info, s.mq_chan)
if err != nil {
log.Error("RedisServer Dial: %s", err)
}
s.redis_server = redis_server
return
}
func (s *RPCServer) SetListener(listener mqrpc.RPCListener) {
s.listener = listener
}
func (s *RPCServer) GetLocalServer() mqrpc.LocalServer {
return s.local_server
}
/**
获取当前正在执行的goroutine 数量
*/
func (s *RPCServer) GetExecuting() int64 {
return s.executing
}
// you must call the function before calling Open and Go
func (s *RPCServer) Register(id string, f interface{}) {
if _, ok := s.functions[id]; ok {
panic(fmt.Sprintf("function id %v: already registered", id))
}
s.functions[id] = *&mqrpc.FunctionInfo{
Function: f,
Goroutine: false,
}
}
// you must call the function before calling Open and Go
func (s *RPCServer) RegisterGO(id string, f interface{}) {
if _, ok := s.functions[id]; ok {
panic(fmt.Sprintf("function id %v: already registered", id))
}
s.functions[id] = *&mqrpc.FunctionInfo{
Function: f,
Goroutine: true,
}
}
func (s *RPCServer) Done() (err error) {
//设置队列停止接收请求
if s.remote_server != nil {
err = s.remote_server.StopConsume()
}
if s.local_server != nil {
err = s.local_server.StopConsume()
}
//等待正在执行的请求完成
close(s.mq_chan) //关闭mq_chan通道
<-s.call_chan_done //mq_chan通道的信息都已处理完
s.wg.Wait()
close(s.callback_chan) //关闭结果发送队列
//关闭队列链接
if s.remote_server != nil {
err = s.remote_server.Shutdown()
}
if s.local_server != nil {
err = s.local_server.Shutdown()
}
return
}
/**
处理结果信息
*/
func (s *RPCServer) on_callback_handle(callbacks <-chan mqrpc.CallInfo) {
for {
select {
case callInfo, ok := <-callbacks:
if !ok {
callbacks = nil
} else {
if callInfo.RpcInfo.Reply {
//需要回复的才回复
callInfo.Agent.(mqrpc.MQServer).Callback(callInfo)
} else {
//对于不需要回复的消息,可以判断一下是否出现错误,打印一些警告
if callInfo.Result.Error != "" {
log.Warning("rpc callback erro :\n%s", callInfo.Result.Error)
}
}
}
}
if callbacks == nil {
break
}
}
}
/**
接收请求信息
*/
func (s *RPCServer) on_call_handle(calls <-chan mqrpc.CallInfo, callbacks chan<- mqrpc.CallInfo, done chan error) {
for {
select {
case callInfo, ok := <-calls:
if !ok {
calls = nil
} else {
if callInfo.RpcInfo.Expired < (time.Now().UnixNano() / 1000000) {
//请求超时了,无需再处理
if s.listener != nil {
s.listener.OnTimeOut(callInfo.RpcInfo.Fn, callInfo.RpcInfo.Expired)
} else {
log.Warning("timeout: This is Call", s.module.GetType(), callInfo.RpcInfo.Fn, callInfo.RpcInfo.Expired, time.Now().UnixNano()/1000000)
}
} else {
s.runFunc(callInfo, callbacks)
}
}
}
if calls == nil {
done <- nil
break
}
}
}
//---------------------------------if _func is not a function or para num and type not match,it will cause panic
func (s *RPCServer) runFunc(callInfo mqrpc.CallInfo, callbacks chan<- mqrpc.CallInfo) {
_errorCallback := func(Cid string, Error string, span opentracing.Span) {
resultInfo := rpcpb.NewResultInfo(Cid, Error, argsutil.NULL, nil)
callInfo.Result = *resultInfo
callbacks <- callInfo
//异常日志都应该打印
log.Error("%s rpc func(%s) error:\n%s", s.module.GetType(), callInfo.RpcInfo.Fn, Error)
if span != nil {
span.LogEventWithPayload("Error", Error)
}
if s.listener != nil {
s.listener.OnError(callInfo.RpcInfo.Fn, &callInfo, fmt.Errorf(Error))
}
}
defer func() {
if r := recover(); r != nil {
var rn = ""
switch r.(type) {
case string:
rn = r.(string)
case error:
rn = r.(error).Error()
}
_errorCallback(callInfo.RpcInfo.Cid, rn, nil)
}
}()
functionInfo, ok := s.functions[callInfo.RpcInfo.Fn]
if !ok {
_errorCallback(callInfo.RpcInfo.Cid, fmt.Sprintf("Remote function(%s) not found", callInfo.RpcInfo.Fn), nil)
return
}
_func := functionInfo.Function
params := callInfo.RpcInfo.Args
ArgsType := callInfo.RpcInfo.ArgsType
f := reflect.ValueOf(_func)
if len(params) != f.Type().NumIn() {
//因为在调研的 _func的时候还会额外传递一个回调函数 cb
_errorCallback(callInfo.RpcInfo.Cid, fmt.Sprintf("The number of params %s is not adapted.%s", params, f.String()), nil)
return
}
//if len(params) != len(callInfo.RpcInfo.ArgsType) {
// //因为在调研的 _func的时候还会额外传递一个回调函数 cb
// _errorCallback(callInfo.RpcInfo.Cid,fmt.Sprintf("The number of params %s is not adapted ArgsType .%s", params, callInfo.RpcInfo.ArgsType))
// return
//}
//typ := reflect.TypeOf(_func)
s.wg.Add(1)
s.executing++
_runFunc := func() {
var span opentracing.Span = nil
defer func() {
if r := recover(); r != nil {
var rn = ""
switch r.(type) {
case string:
rn = r.(string)
case error:
rn = r.(error).Error()
}
buf := make([]byte, 1024)
l := runtime.Stack(buf, false)
errstr := string(buf[:l])
allError := fmt.Sprintf("%s rpc func(%s) error %s\n ----Stack----\n%s", s.module.GetType(), callInfo.RpcInfo.Fn, rn, errstr)
//log.Error(allError)
_errorCallback(callInfo.RpcInfo.Cid, allError, span)
}
if span != nil {
span.Finish()
}
s.wg.Add(-1)
s.executing--
}()
exec_time := time.Now().UnixNano()
//t:=RandInt64(2,3)
//time.Sleep(time.Second*time.Duration(t))
// f 为函数地址
var session gate.Session = nil
var in []reflect.Value
if len(ArgsType) > 0 {
in = make([]reflect.Value, len(params))
for k, v := range ArgsType {
v, err := argsutil.Bytes2Args(s.app, v, params[k])
if err != nil {
_errorCallback(callInfo.RpcInfo.Cid, err.Error(), span)
return
}
switch v2 := v.(type) { //多选语句switch
case gate.Session:
//尝试加载Span
span = v2.LoadSpan(fmt.Sprintf("%s/%s", s.module.GetType(), callInfo.RpcInfo.Fn))
if span != nil {
span.SetTag("UserId", v2.GetUserid())
span.SetTag("Func", callInfo.RpcInfo.Fn)
}
session = v2
in[k] = reflect.ValueOf(v)
case nil:
in[k] = reflect.Zero(f.Type().In(k))
default:
in[k] = reflect.ValueOf(v)
}
}
}
if s.listener != nil {
errs := s.listener.BeforeHandle(callInfo.RpcInfo.Fn, session, &callInfo)
if errs != nil {
_errorCallback(callInfo.RpcInfo.Cid, errs.Error(), span)
return
}
}
out := f.Call(in)
var rs []interface{}
if len(out) != 2 {
_errorCallback(callInfo.RpcInfo.Cid, "The number of prepare is not adapted.", span)
return
}
if len(out) > 0 { //prepare out paras
rs = make([]interface{}, len(out), len(out))
for i, v := range out {
rs[i] = v.Interface()
}
}
argsType, args, err := argsutil.ArgsTypeAnd2Bytes(s.app, rs[0])
if err != nil {
_errorCallback(callInfo.RpcInfo.Cid, err.Error(), span)
return
}
resultInfo := rpcpb.NewResultInfo(
callInfo.RpcInfo.Cid,
rs[1].(string),
argsType,
args,
)
callInfo.Result = *resultInfo
callbacks <- callInfo
if span != nil {
span.LogEventWithPayload("Result.Type", argsType)
span.LogEventWithPayload("Result", string(args))
}
if s.app.GetSettings().Rpc.LogSuccess {
log.Info("%s rpc func(%s) exec_time(%s) success", s.module.GetType(), callInfo.RpcInfo.Fn, s.timeConversion(time.Now().UnixNano()-exec_time))
}
if s.listener != nil {
s.listener.OnComplete(callInfo.RpcInfo.Fn, &callInfo, resultInfo, time.Now().UnixNano()-exec_time)
}
}
if functionInfo.Goroutine {
go _runFunc()
} else {
_runFunc()
}
}
func (s *RPCServer) timeConversion(ns int64) string {
if (ns / 1000) < 1 {
return fmt.Sprintf("%.2f ns", (ns))
} else if 1 < (ns/int64(1000)) && (ns/int64(1000)) < 1000 {
return fmt.Sprintf("%.2f μs", float32(ns/int64(1000)))
} else if 1 < (ns/int64(1000*1000)) && (ns/int64(1000*1000)) < 1000 {
return fmt.Sprintf("%.2f ms", float32(ns/int64(1000*1000)))
} else if 1 < (ns/int64(1000*1000*1000)) && (ns/int64(1000*1000*1000)) < 1000 {
return fmt.Sprintf("%.2f s", float32(ns/int64(1000*1000*1000)))
} else if 1 < (ns/int64(1000*1000*1000*60)) && (ns/int64(1000*1000*1000*60)) < 1000 {
return fmt.Sprintf("%.2f m", float32(ns/int64(1000*1000*1000*60)))
} else if 1 < (ns/int64(1000*1000*1000*60*60)) && (ns/int64(1000*1000*1000*60*60)) < 1000 {
return fmt.Sprintf("%.2f m", float32(ns/int64(1000*1000*1000*60*60)))
} else {
return fmt.Sprintf("%.2f ns", (ns))
}
}