github.com/zjj1991/quorum@v0.0.0-20190524123704-ae4b0a1e1a19/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 mapset "github.com/deckarep/golang-set" 29 "github.com/ethereum/go-ethereum/log" 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: mapset.NewSet(), 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 if len(methods) == 0 && len(subscriptions) == 0 { 98 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 99 } 100 101 // already a previous service register under given name, merge methods/subscriptions 102 if regsvc, present := s.services[name]; present { 103 for _, m := range methods { 104 regsvc.callbacks[formatName(m.method.Name)] = m 105 } 106 for _, s := range subscriptions { 107 regsvc.subscriptions[formatName(s.method.Name)] = s 108 } 109 return nil 110 } 111 112 svc.name = name 113 svc.callbacks, svc.subscriptions = methods, subscriptions 114 115 s.services[svc.name] = svc 116 return nil 117 } 118 119 // serveRequest will reads requests from the codec, calls the RPC callback and 120 // writes the response to the given codec. 121 // 122 // If singleShot is true it will process a single request, otherwise it will handle 123 // requests until the codec returns an error when reading a request (in most cases 124 // an EOF). It executes requests in parallel when singleShot is false. 125 func (s *Server) serveRequest(ctx context.Context, codec ServerCodec, singleShot bool, options CodecOption) error { 126 var pend sync.WaitGroup 127 128 defer func() { 129 if err := recover(); err != nil { 130 const size = 64 << 10 131 buf := make([]byte, size) 132 buf = buf[:runtime.Stack(buf, false)] 133 log.Error(string(buf)) 134 } 135 s.codecsMu.Lock() 136 s.codecs.Remove(codec) 137 s.codecsMu.Unlock() 138 }() 139 140 // ctx, cancel := context.WithCancel(context.Background()) 141 ctx, cancel := context.WithCancel(ctx) 142 defer cancel() 143 144 // if the codec supports notification include a notifier that callbacks can use 145 // to send notification to clients. It is tied to the codec/connection. If the 146 // connection is closed the notifier will stop and cancels all active subscriptions. 147 if options&OptionSubscriptions == OptionSubscriptions { 148 ctx = context.WithValue(ctx, notifierKey{}, newNotifier(codec)) 149 } 150 s.codecsMu.Lock() 151 if atomic.LoadInt32(&s.run) != 1 { // server stopped 152 s.codecsMu.Unlock() 153 return &shutdownError{} 154 } 155 s.codecs.Add(codec) 156 s.codecsMu.Unlock() 157 158 // test if the server is ordered to stop 159 for atomic.LoadInt32(&s.run) == 1 { 160 reqs, batch, err := s.readRequest(codec) 161 if err != nil { 162 // If a parsing error occurred, send an error 163 if err.Error() != "EOF" { 164 log.Debug(fmt.Sprintf("read error %v\n", err)) 165 codec.Write(codec.CreateErrorResponse(nil, err)) 166 } 167 // Error or end of stream, wait for requests and tear down 168 pend.Wait() 169 return nil 170 } 171 172 // check if server is ordered to shutdown and return an error 173 // telling the client that his request failed. 174 if atomic.LoadInt32(&s.run) != 1 { 175 err = &shutdownError{} 176 if batch { 177 resps := make([]interface{}, len(reqs)) 178 for i, r := range reqs { 179 resps[i] = codec.CreateErrorResponse(&r.id, err) 180 } 181 codec.Write(resps) 182 } else { 183 codec.Write(codec.CreateErrorResponse(&reqs[0].id, err)) 184 } 185 return nil 186 } 187 // If a single shot request is executing, run and return immediately 188 if singleShot { 189 if batch { 190 s.execBatch(ctx, codec, reqs) 191 } else { 192 s.exec(ctx, codec, reqs[0]) 193 } 194 return nil 195 } 196 // For multi-shot connections, start a goroutine to serve and loop back 197 pend.Add(1) 198 199 go func(reqs []*serverRequest, batch bool) { 200 defer pend.Done() 201 if batch { 202 s.execBatch(ctx, codec, reqs) 203 } else { 204 s.exec(ctx, codec, reqs[0]) 205 } 206 }(reqs, batch) 207 } 208 return nil 209 } 210 211 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the 212 // response back using the given codec. It will block until the codec is closed or the server is 213 // stopped. In either case the codec is closed. 214 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 215 defer codec.Close() 216 s.serveRequest(context.Background(), codec, false, options) 217 } 218 219 // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not 220 // close the codec unless a non-recoverable error has occurred. Note, this method will return after 221 // a single request has been processed! 222 func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec, options CodecOption) { 223 s.serveRequest(ctx, codec, true, options) 224 } 225 226 // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, 227 // close all codecs which will cancel pending requests/subscriptions. 228 func (s *Server) Stop() { 229 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 230 log.Debug("RPC Server shutdown initiatied") 231 s.codecsMu.Lock() 232 defer s.codecsMu.Unlock() 233 s.codecs.Each(func(c interface{}) bool { 234 c.(ServerCodec).Close() 235 return true 236 }) 237 } 238 } 239 240 // createSubscription will call the subscription callback and returns the subscription id or error. 241 func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) { 242 // subscription have as first argument the context following optional arguments 243 args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)} 244 args = append(args, req.args...) 245 reply := req.callb.method.Func.Call(args) 246 247 if !reply[1].IsNil() { // subscription creation failed 248 return "", reply[1].Interface().(error) 249 } 250 251 return reply[0].Interface().(*Subscription).ID, nil 252 } 253 254 // handle executes a request and returns the response from the callback. 255 func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) { 256 if req.err != nil { 257 return codec.CreateErrorResponse(&req.id, req.err), nil 258 } 259 260 if req.isUnsubscribe { // cancel subscription, first param must be the subscription id 261 if len(req.args) >= 1 && req.args[0].Kind() == reflect.String { 262 notifier, supported := NotifierFromContext(ctx) 263 if !supported { // interface doesn't support subscriptions (e.g. http) 264 return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil 265 } 266 267 subid := ID(req.args[0].String()) 268 if err := notifier.unsubscribe(subid); err != nil { 269 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 270 } 271 272 return codec.CreateResponse(req.id, true), nil 273 } 274 return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil 275 } 276 277 if req.callb.isSubscribe { 278 subid, err := s.createSubscription(ctx, codec, req) 279 if err != nil { 280 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 281 } 282 283 // active the subscription after the sub id was successfully sent to the client 284 activateSub := func() { 285 notifier, _ := NotifierFromContext(ctx) 286 notifier.activate(subid, req.svcname) 287 } 288 289 return codec.CreateResponse(req.id, subid), activateSub 290 } 291 292 // regular RPC call, prepare arguments 293 if len(req.args) != len(req.callb.argTypes) { 294 rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d", 295 req.svcname, serviceMethodSeparator, req.callb.method.Name, 296 len(req.callb.argTypes), len(req.args))} 297 return codec.CreateErrorResponse(&req.id, rpcErr), nil 298 } 299 300 //Quorum 301 //Pass the request ID to the method as part of the context, in case the method needs it later 302 contextWithId := context.WithValue(ctx, "id", req.id) 303 //End-Quorum 304 arguments := []reflect.Value{req.callb.rcvr} 305 if req.callb.hasCtx { 306 arguments = append(arguments, reflect.ValueOf(contextWithId)) 307 } 308 if len(req.args) > 0 { 309 arguments = append(arguments, req.args...) 310 } 311 312 // execute RPC method and return result 313 reply := req.callb.method.Func.Call(arguments) 314 if len(reply) == 0 { 315 return codec.CreateResponse(req.id, nil), nil 316 } 317 if req.callb.errPos >= 0 { // test if method returned an error 318 if !reply[req.callb.errPos].IsNil() { 319 e := reply[req.callb.errPos].Interface().(error) 320 res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()}) 321 return res, nil 322 } 323 } 324 return codec.CreateResponse(req.id, reply[0].Interface()), nil 325 } 326 327 // exec executes the given request and writes the result back using the codec. 328 func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) { 329 var response interface{} 330 var callback func() 331 if req.err != nil { 332 response = codec.CreateErrorResponse(&req.id, req.err) 333 } else { 334 response, callback = s.handle(ctx, codec, req) 335 } 336 337 if err := codec.Write(response); err != nil { 338 log.Error(fmt.Sprintf("%v\n", err)) 339 codec.Close() 340 } 341 342 // when request was a subscribe request this allows these subscriptions to be actived 343 if callback != nil { 344 callback() 345 } 346 } 347 348 // execBatch executes the given requests and writes the result back using the codec. 349 // It will only write the response back when the last request is processed. 350 func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) { 351 responses := make([]interface{}, len(requests)) 352 var callbacks []func() 353 for i, req := range requests { 354 if req.err != nil { 355 responses[i] = codec.CreateErrorResponse(&req.id, req.err) 356 } else { 357 var callback func() 358 if responses[i], callback = s.handle(ctx, codec, req); callback != nil { 359 callbacks = append(callbacks, callback) 360 } 361 } 362 } 363 364 if err := codec.Write(responses); err != nil { 365 log.Error(fmt.Sprintf("%v\n", err)) 366 codec.Close() 367 } 368 369 // when request holds one of more subscribe requests this allows these subscriptions to be activated 370 for _, c := range callbacks { 371 c() 372 } 373 } 374 375 // readRequest requests the next (batch) request from the codec. It will return the collection 376 // of requests, an indication if the request was a batch, the invalid request identifier and an 377 // error when the request could not be read/parsed. 378 func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) { 379 reqs, batch, err := codec.ReadRequestHeaders() 380 if err != nil { 381 return nil, batch, err 382 } 383 384 requests := make([]*serverRequest, len(reqs)) 385 386 // verify requests 387 for i, r := range reqs { 388 var ok bool 389 var svc *service 390 391 if r.err != nil { 392 requests[i] = &serverRequest{id: r.id, err: r.err} 393 continue 394 } 395 396 if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) { 397 requests[i] = &serverRequest{id: r.id, isUnsubscribe: true} 398 argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg 399 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 400 requests[i].args = args 401 } else { 402 requests[i].err = &invalidParamsError{err.Error()} 403 } 404 continue 405 } 406 407 if svc, ok = s.services[r.service]; !ok { // rpc method isn't available 408 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 409 continue 410 } 411 412 if r.isPubSub { // eth_subscribe, r.method contains the subscription method name 413 if callb, ok := svc.subscriptions[r.method]; ok { 414 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 415 if r.params != nil && len(callb.argTypes) > 0 { 416 argTypes := []reflect.Type{reflect.TypeOf("")} 417 argTypes = append(argTypes, callb.argTypes...) 418 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 419 requests[i].args = args[1:] // first one is service.method name which isn't an actual argument 420 } else { 421 requests[i].err = &invalidParamsError{err.Error()} 422 } 423 } 424 } else { 425 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 426 } 427 continue 428 } 429 430 if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method 431 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 432 if r.params != nil && len(callb.argTypes) > 0 { 433 if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil { 434 requests[i].args = args 435 } else { 436 requests[i].err = &invalidParamsError{err.Error()} 437 } 438 } 439 continue 440 } 441 442 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 443 } 444 445 return requests, batch, nil 446 }