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