github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/rpc/server.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rpc 18 19 import ( 20 "context" 21 "fmt" 22 "reflect" 23 "runtime" 24 "strings" 25 "sync" 26 "sync/atomic" 27 28 "github.com/vntchain/go-vnt/log" 29 "gopkg.in/fatih/set.v0" 30 ) 31 32 const MetadataApi = "rpc" 33 34 // CodecOption specifies which type of messages this codec supports 35 type CodecOption int 36 37 const ( 38 // OptionMethodInvocation is an indication that the codec supports RPC method calls 39 OptionMethodInvocation CodecOption = 1 << iota 40 41 // OptionSubscriptions is an indication that the codec suports RPC notifications 42 OptionSubscriptions = 1 << iota // support pub sub 43 ) 44 45 // NewServer will create a new server instance with no registered handlers. 46 func NewServer() *Server { 47 server := &Server{ 48 services: make(serviceRegistry), 49 codecs: set.New(), 50 run: 1, 51 } 52 53 // register a default service which will provide meta information about the RPC service such as the services and 54 // methods it offers. 55 rpcService := &RPCService{server} 56 server.RegisterName(MetadataApi, rpcService) 57 58 return server 59 } 60 61 // RPCService gives meta information about the server. 62 // e.g. gives information about the loaded modules. 63 type RPCService struct { 64 server *Server 65 } 66 67 // Modules returns the list of RPC services with their version number 68 func (s *RPCService) Modules() map[string]string { 69 modules := make(map[string]string) 70 for name := range s.server.services { 71 modules[name] = "1.0" 72 } 73 return modules 74 } 75 76 // RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr 77 // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is 78 // created and added to the service collection this server instance serves. 79 func (s *Server) RegisterName(name string, rcvr interface{}) error { 80 if s.services == nil { 81 s.services = make(serviceRegistry) 82 } 83 84 svc := new(service) 85 svc.typ = reflect.TypeOf(rcvr) 86 rcvrVal := reflect.ValueOf(rcvr) 87 88 if name == "" { 89 return fmt.Errorf("no service name for type %s", svc.typ.String()) 90 } 91 if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { 92 return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) 93 } 94 95 methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) 96 97 // already a previous service register under given sname, merge methods/subscriptions 98 if regsvc, present := s.services[name]; present { 99 if len(methods) == 0 && len(subscriptions) == 0 { 100 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 101 } 102 for _, m := range methods { 103 regsvc.callbacks[formatName(m.method.Name)] = m 104 } 105 for _, s := range subscriptions { 106 regsvc.subscriptions[formatName(s.method.Name)] = s 107 } 108 return nil 109 } 110 111 svc.name = name 112 svc.callbacks, svc.subscriptions = methods, subscriptions 113 114 if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 { 115 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 116 } 117 118 s.services[svc.name] = svc 119 return nil 120 } 121 122 // serveRequest will reads requests from the codec, calls the RPC callback and 123 // writes the response to the given codec. 124 // 125 // If singleShot is true it will process a single request, otherwise it will handle 126 // requests until the codec returns an error when reading a request (in most cases 127 // an EOF). It executes requests in parallel when singleShot is false. 128 func (s *Server) serveRequest(ctx context.Context, codec ServerCodec, singleShot bool, options CodecOption) error { 129 var pend sync.WaitGroup 130 131 defer func() { 132 if err := recover(); err != nil { 133 const size = 64 << 10 134 buf := make([]byte, size) 135 buf = buf[:runtime.Stack(buf, false)] 136 log.Error(string(buf)) 137 } 138 s.codecsMu.Lock() 139 s.codecs.Remove(codec) 140 s.codecsMu.Unlock() 141 }() 142 143 // ctx, cancel := context.WithCancel(context.Background()) 144 ctx, cancel := context.WithCancel(ctx) 145 defer cancel() 146 147 // if the codec supports notification include a notifier that callbacks can use 148 // to send notification to clients. It is tied to the codec/connection. If the 149 // connection is closed the notifier will stop and cancels all active subscriptions. 150 if options&OptionSubscriptions == OptionSubscriptions { 151 ctx = context.WithValue(ctx, notifierKey{}, newNotifier(codec)) 152 } 153 s.codecsMu.Lock() 154 if atomic.LoadInt32(&s.run) != 1 { // server stopped 155 s.codecsMu.Unlock() 156 return &shutdownError{} 157 } 158 s.codecs.Add(codec) 159 s.codecsMu.Unlock() 160 161 // test if the server is ordered to stop 162 for atomic.LoadInt32(&s.run) == 1 { 163 reqs, batch, err := s.readRequest(codec) 164 if err != nil { 165 // If a parsing error occurred, send an error 166 if err.Error() != "EOF" { 167 log.Debug(fmt.Sprintf("read error %v\n", err)) 168 codec.Write(codec.CreateErrorResponse(nil, err)) 169 } 170 // Error or end of stream, wait for requests and tear down 171 pend.Wait() 172 return nil 173 } 174 175 // check if server is ordered to shutdown and return an error 176 // telling the client that his request failed. 177 if atomic.LoadInt32(&s.run) != 1 { 178 err = &shutdownError{} 179 if batch { 180 resps := make([]interface{}, len(reqs)) 181 for i, r := range reqs { 182 resps[i] = codec.CreateErrorResponse(&r.id, err) 183 } 184 codec.Write(resps) 185 } else { 186 codec.Write(codec.CreateErrorResponse(&reqs[0].id, err)) 187 } 188 return nil 189 } 190 // If a single shot request is executing, run and return immediately 191 if singleShot { 192 if batch { 193 s.execBatch(ctx, codec, reqs) 194 } else { 195 s.exec(ctx, codec, reqs[0]) 196 } 197 return nil 198 } 199 // For multi-shot connections, start a goroutine to serve and loop back 200 pend.Add(1) 201 202 go func(reqs []*serverRequest, batch bool) { 203 defer pend.Done() 204 if batch { 205 s.execBatch(ctx, codec, reqs) 206 } else { 207 s.exec(ctx, codec, reqs[0]) 208 } 209 }(reqs, batch) 210 } 211 return nil 212 } 213 214 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the 215 // response back using the given codec. It will block until the codec is closed or the server is 216 // stopped. In either case the codec is closed. 217 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 218 defer codec.Close() 219 s.serveRequest(context.Background(), codec, false, options) 220 } 221 222 // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not 223 // close the codec unless a non-recoverable error has occurred. Note, this method will return after 224 // a single request has been processed! 225 func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec, options CodecOption) { 226 s.serveRequest(ctx, codec, true, options) 227 } 228 229 // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, 230 // close all codecs which will cancel pending requests/subscriptions. 231 func (s *Server) Stop() { 232 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 233 log.Debug("RPC Server shutdown initiatied") 234 s.codecsMu.Lock() 235 defer s.codecsMu.Unlock() 236 s.codecs.Each(func(c interface{}) bool { 237 c.(ServerCodec).Close() 238 return true 239 }) 240 } 241 } 242 243 // createSubscription will call the subscription callback and returns the subscription id or error. 244 func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) { 245 // subscription have as first argument the context following optional arguments 246 args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)} 247 args = append(args, req.args...) 248 reply := req.callb.method.Func.Call(args) 249 250 if !reply[1].IsNil() { // subscription creation failed 251 return "", reply[1].Interface().(error) 252 } 253 254 return reply[0].Interface().(*Subscription).ID, nil 255 } 256 257 // handle executes a request and returns the response from the callback. 258 func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) { 259 if req.err != nil { 260 return codec.CreateErrorResponse(&req.id, req.err), nil 261 } 262 263 if req.isUnsubscribe { // cancel subscription, first param must be the subscription id 264 if len(req.args) >= 1 && req.args[0].Kind() == reflect.String { 265 notifier, supported := NotifierFromContext(ctx) 266 if !supported { // interface doesn't support subscriptions (e.g. http) 267 return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil 268 } 269 270 subid := ID(req.args[0].String()) 271 if err := notifier.unsubscribe(subid); err != nil { 272 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 273 } 274 275 return codec.CreateResponse(req.id, true), nil 276 } 277 return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil 278 } 279 280 if req.callb.isSubscribe { 281 subid, err := s.createSubscription(ctx, codec, req) 282 if err != nil { 283 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 284 } 285 286 // active the subscription after the sub id was successfully sent to the client 287 activateSub := func() { 288 notifier, _ := NotifierFromContext(ctx) 289 notifier.activate(subid, req.svcname) 290 } 291 292 return codec.CreateResponse(req.id, subid), activateSub 293 } 294 295 // regular RPC call, prepare arguments 296 if len(req.args) != len(req.callb.argTypes) { 297 rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d", 298 req.svcname, serviceMethodSeparator, req.callb.method.Name, 299 len(req.callb.argTypes), len(req.args))} 300 return codec.CreateErrorResponse(&req.id, rpcErr), nil 301 } 302 303 arguments := []reflect.Value{req.callb.rcvr} 304 if req.callb.hasCtx { 305 arguments = append(arguments, reflect.ValueOf(ctx)) 306 } 307 if len(req.args) > 0 { 308 arguments = append(arguments, req.args...) 309 } 310 311 // execute RPC method and return result 312 reply := req.callb.method.Func.Call(arguments) 313 if len(reply) == 0 { 314 return codec.CreateResponse(req.id, nil), nil 315 } 316 if req.callb.errPos >= 0 { // test if method returned an error 317 if !reply[req.callb.errPos].IsNil() { 318 e := reply[req.callb.errPos].Interface().(error) 319 res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()}) 320 return res, nil 321 } 322 } 323 return codec.CreateResponse(req.id, reply[0].Interface()), nil 324 } 325 326 // exec executes the given request and writes the result back using the codec. 327 func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) { 328 var response interface{} 329 var callback func() 330 if req.err != nil { 331 response = codec.CreateErrorResponse(&req.id, req.err) 332 } else { 333 response, callback = s.handle(ctx, codec, req) 334 } 335 336 if err := codec.Write(response); err != nil { 337 log.Error(fmt.Sprintf("%v\n", err)) 338 codec.Close() 339 } 340 341 // when request was a subscribe request this allows these subscriptions to be actived 342 if callback != nil { 343 callback() 344 } 345 } 346 347 // execBatch executes the given requests and writes the result back using the codec. 348 // It will only write the response back when the last request is processed. 349 func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) { 350 responses := make([]interface{}, len(requests)) 351 var callbacks []func() 352 for i, req := range requests { 353 if req.err != nil { 354 responses[i] = codec.CreateErrorResponse(&req.id, req.err) 355 } else { 356 var callback func() 357 if responses[i], callback = s.handle(ctx, codec, req); callback != nil { 358 callbacks = append(callbacks, callback) 359 } 360 } 361 } 362 363 if err := codec.Write(responses); err != nil { 364 log.Error(fmt.Sprintf("%v\n", err)) 365 codec.Close() 366 } 367 368 // when request holds one of more subscribe requests this allows these subscriptions to be activated 369 for _, c := range callbacks { 370 c() 371 } 372 } 373 374 // readRequest requests the next (batch) request from the codec. It will return the collection 375 // of requests, an indication if the request was a batch, the invalid request identifier and an 376 // error when the request could not be read/parsed. 377 func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) { 378 reqs, batch, err := codec.ReadRequestHeaders() 379 if err != nil { 380 return nil, batch, err 381 } 382 383 requests := make([]*serverRequest, len(reqs)) 384 385 // verify requests 386 for i, r := range reqs { 387 var ok bool 388 var svc *service 389 390 if r.err != nil { 391 requests[i] = &serverRequest{id: r.id, err: r.err} 392 continue 393 } 394 395 if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) { 396 requests[i] = &serverRequest{id: r.id, isUnsubscribe: true} 397 argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg 398 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 399 requests[i].args = args 400 } else { 401 requests[i].err = &invalidParamsError{err.Error()} 402 } 403 continue 404 } 405 406 if svc, ok = s.services[r.service]; !ok { // rpc method isn't available 407 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 408 continue 409 } 410 411 if r.isPubSub { // core_subscribe, r.method contains the subscription method name 412 if callb, ok := svc.subscriptions[r.method]; ok { 413 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 414 if r.params != nil && len(callb.argTypes) > 0 { 415 argTypes := []reflect.Type{reflect.TypeOf("")} 416 argTypes = append(argTypes, callb.argTypes...) 417 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 418 requests[i].args = args[1:] // first one is service.method name which isn't an actual argument 419 } else { 420 requests[i].err = &invalidParamsError{err.Error()} 421 } 422 } 423 } else { 424 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 425 } 426 continue 427 } 428 429 if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method 430 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 431 if r.params != nil && len(callb.argTypes) > 0 { 432 if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil { 433 requests[i].args = args 434 } else { 435 requests[i].err = &invalidParamsError{err.Error()} 436 } 437 } 438 continue 439 } 440 441 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 442 } 443 444 return requests, batch, nil 445 }