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