forked from lubanproj/gorpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
executable file
·280 lines (211 loc) · 6.08 KB
/
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
package gorpc
import (
"context"
"fmt"
"os"
"os/signal"
"reflect"
"syscall"
"github.com/lubanproj/gorpc/interceptor"
"github.com/lubanproj/gorpc/log"
"github.com/lubanproj/gorpc/plugin"
"github.com/lubanproj/gorpc/plugin/jaeger"
)
// gorpc Server 一个服务器可以有一个或多个服务
type Server struct {
opts *ServerOptions
service Service
plugins []plugin.Plugin
closing bool // 服务器是否正在关闭
}
// NewServer creates a Server, Support to pass in ServerOption parameters
func NewServer(opt ...ServerOption) *Server {
s := &Server{
opts: &ServerOptions{},
}
for _, o := range opt {
o(s.opts)
}
s.service = NewService(s.opts)
for pluginName, plugin := range plugin.PluginMap {
if !containPlugin(pluginName, s.opts.pluginNames) {
continue
}
s.plugins = append(s.plugins, plugin)
}
return s
}
func NewService(opts *ServerOptions) Service {
return &service{
opts: opts,
}
}
func containPlugin(pluginName string, plugins []string) bool {
for _, plugin := range plugins {
if pluginName == plugin {
return true
}
}
return false
}
type emptyInterface interface{}
func (s *Server) RegisterService(serviceName string, svr interface{}) error {
svrType := reflect.TypeOf(svr)
svrValue := reflect.ValueOf(svr)
sd := &ServiceDesc{
ServiceName: serviceName,
// for compatibility with code generation
HandlerType: (*emptyInterface)(nil),
Svr: svr,
}
methods, err := getServiceMethods(svrType, svrValue)
if err != nil {
return err
}
sd.Methods = methods
s.Register(sd, svr)
return nil
}
func getServiceMethods(serviceType reflect.Type, serviceValue reflect.Value) ([]*MethodDesc, error) {
var methods []*MethodDesc
for i := 0; i < serviceType.NumMethod(); i++ {
method := serviceType.Method(i)
if err := checkMethod(method.Type); err != nil {
return nil, err
}
methodHandler := func(ctx context.Context, svr interface{}, dec func(interface{}) error, ceps []interceptor.ServerInterceptor) (interface{}, error) {
reqType := method.Type.In(2)
// determine type
req := reflect.New(reqType.Elem()).Interface()
if err := dec(req); err != nil {
return nil, err
}
if len(ceps) == 0 {
values := method.Func.Call([]reflect.Value{serviceValue, reflect.ValueOf(ctx), reflect.ValueOf(req)})
// determine error
return values[0].Interface(), nil
}
handler := func(ctx context.Context, reqbody interface{}) (interface{}, error) {
values := method.Func.Call([]reflect.Value{serviceValue, reflect.ValueOf(ctx), reflect.ValueOf(req)})
return values[0].Interface(), nil
}
return interceptor.ServerIntercept(ctx, req, ceps, handler)
}
methods = append(methods, &MethodDesc{
MethodName: method.Name,
Handler: methodHandler,
})
}
return methods, nil
}
func checkMethod(method reflect.Type) error {
// params num must >= 2 , needs to be combined with itself
if method.NumIn() < 3 {
return fmt.Errorf("method %s invalid, the number of params < 2", method.Name())
}
// return values nums must be 2
if method.NumOut() != 2 {
return fmt.Errorf("method %s invalid, the number of return values != 2", method.Name())
}
// the first parameter must be context
ctxType := method.In(1)
var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
if !ctxType.Implements(contextType) {
return fmt.Errorf("method %s invalid, first param is not context", method.Name())
}
// the second parameter type must be pointer
argType := method.In(2)
if argType.Kind() != reflect.Ptr {
return fmt.Errorf("method %s invalid, req type is not a pointer", method.Name())
}
// the first return type must be a pointer
replyType := method.Out(0)
if replyType.Kind() != reflect.Ptr {
return fmt.Errorf("method %s invalid, reply type is not a pointer", method.Name())
}
// The second return value must be an error
errType := method.Out(1)
var errorType = reflect.TypeOf((*error)(nil)).Elem()
if !errType.Implements(errorType) {
return fmt.Errorf("method %s invalid, returns %s , not error", method.Name(), errType.Name())
}
return nil
}
func (s *Server) Register(sd *ServiceDesc, svr interface{}) {
if sd == nil || svr == nil {
return
}
ht := reflect.TypeOf(sd.HandlerType).Elem()
st := reflect.TypeOf(svr)
if !st.Implements(ht) {
log.Fatalf("handlerType %v not match service : %v ", ht, st)
}
ser := &service{
svr: svr,
serviceName: sd.ServiceName,
handlers: make(map[string]Handler),
}
for _, method := range sd.Methods {
ser.handlers[method.MethodName] = method.Handler
}
s.service = ser
}
func (s *Server) Serve() {
err := s.InitPlugins()
if err != nil {
panic(err)
}
s.service.Serve(s.opts)
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGSEGV)
<-ch
s.Close()
}
type emptyService struct{}
func (s *Server) ServeHttp() {
if err := s.RegisterService("/http", new(emptyService)); err != nil {
panic(err)
}
s.Serve()
}
func (s *Server) Close() {
s.closing = false
s.service.Close()
}
// 初始化插件
func (s *Server) InitPlugins() error {
// init plugins
for _, p := range s.plugins {
// 获取插件的类型
switch val := p.(type) {
// 如果是服务发现插件
case plugin.ResolverPlugin:
var services []string
services = append(services, s.service.Name())
pluginOpts := []plugin.Option{
plugin.WithSelectorSvrAddr(s.opts.selectorSvrAddr),
plugin.WithSvrAddr(s.opts.address),
plugin.WithServices(services),
}
if err := val.Init(pluginOpts...); err != nil {
log.Errorf("resolver init error, %v", err)
return err
}
// 如果是链路追踪插件
case plugin.TracingPlugin:
pluginOpts := []plugin.Option{
plugin.WithTracingSvrAddr(s.opts.tracingSvrAddr),
}
// 初始化插件
tracer, err := val.Init(pluginOpts...)
if err != nil {
log.Errorf("tracing init error, %v", err)
return err
}
// server 的拦截器自动添加 链路追踪的拦截器
s.opts.interceptors = append(s.opts.interceptors, jaeger.OpenTracingServerInterceptor(tracer, s.opts.tracingSpanName))
default:
}
}
return nil
}