github.com/etherbanking/go-etherbanking@v1.7.1-0.20181009210156-cf649bca5aba/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/etherbanking/go-etherbanking/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(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 defer cancel() 145 146 // if the codec supports notification include a notifier that callbacks can use 147 // to send notification to clients. It is thight 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.Add(codec) 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 codec.Write(codec.CreateErrorResponse(nil, err)) 168 } 169 // Error or end of stream, wait for requests and tear down 170 pend.Wait() 171 return nil 172 } 173 174 // check if server is ordered to shutdown and return an error 175 // telling the client that his request failed. 176 if atomic.LoadInt32(&s.run) != 1 { 177 err = &shutdownError{} 178 if batch { 179 resps := make([]interface{}, len(reqs)) 180 for i, r := range reqs { 181 resps[i] = codec.CreateErrorResponse(&r.id, err) 182 } 183 codec.Write(resps) 184 } else { 185 codec.Write(codec.CreateErrorResponse(&reqs[0].id, err)) 186 } 187 return nil 188 } 189 // If a single shot request is executing, run and return immediately 190 if singleShot { 191 if batch { 192 s.execBatch(ctx, codec, reqs) 193 } else { 194 s.exec(ctx, codec, reqs[0]) 195 } 196 return nil 197 } 198 // For multi-shot connections, start a goroutine to serve and loop back 199 pend.Add(1) 200 201 go func(reqs []*serverRequest, batch bool) { 202 defer pend.Done() 203 if batch { 204 s.execBatch(ctx, codec, reqs) 205 } else { 206 s.exec(ctx, codec, reqs[0]) 207 } 208 }(reqs, batch) 209 } 210 return nil 211 } 212 213 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the 214 // response back using the given codec. It will block until the codec is closed or the server is 215 // stopped. In either case the codec is closed. 216 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 217 defer codec.Close() 218 s.serveRequest(codec, false, options) 219 } 220 221 // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not 222 // close the codec unless a non-recoverable error has occurred. Note, this method will return after 223 // a single request has been processed! 224 func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption) { 225 s.serveRequest(codec, true, options) 226 } 227 228 // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, 229 // close all codecs which will cancel pending requests/subscriptions. 230 func (s *Server) Stop() { 231 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 232 log.Debug("RPC Server shutdown initiatied") 233 s.codecsMu.Lock() 234 defer s.codecsMu.Unlock() 235 s.codecs.Each(func(c interface{}) bool { 236 c.(ServerCodec).Close() 237 return true 238 }) 239 } 240 } 241 242 // createSubscription will call the subscription callback and returns the subscription id or error. 243 func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) { 244 // subscription have as first argument the context following optional arguments 245 args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)} 246 args = append(args, req.args...) 247 reply := req.callb.method.Func.Call(args) 248 249 if !reply[1].IsNil() { // subscription creation failed 250 return "", reply[1].Interface().(error) 251 } 252 253 return reply[0].Interface().(*Subscription).ID, nil 254 } 255 256 // handle executes a request and returns the response from the callback. 257 func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) { 258 if req.err != nil { 259 return codec.CreateErrorResponse(&req.id, req.err), nil 260 } 261 262 if req.isUnsubscribe { // cancel subscription, first param must be the subscription id 263 if len(req.args) >= 1 && req.args[0].Kind() == reflect.String { 264 notifier, supported := NotifierFromContext(ctx) 265 if !supported { // interface doesn't support subscriptions (e.g. http) 266 return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil 267 } 268 269 subid := ID(req.args[0].String()) 270 if err := notifier.unsubscribe(subid); err != nil { 271 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 272 } 273 274 return codec.CreateResponse(req.id, true), nil 275 } 276 return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil 277 } 278 279 if req.callb.isSubscribe { 280 subid, err := s.createSubscription(ctx, codec, req) 281 if err != nil { 282 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 283 } 284 285 // active the subscription after the sub id was successfully sent to the client 286 activateSub := func() { 287 notifier, _ := NotifierFromContext(ctx) 288 notifier.activate(subid, req.svcname) 289 } 290 291 return codec.CreateResponse(req.id, subid), activateSub 292 } 293 294 // regular RPC call, prepare arguments 295 if len(req.args) != len(req.callb.argTypes) { 296 rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d", 297 req.svcname, serviceMethodSeparator, req.callb.method.Name, 298 len(req.callb.argTypes), len(req.args))} 299 return codec.CreateErrorResponse(&req.id, rpcErr), nil 300 } 301 302 arguments := []reflect.Value{req.callb.rcvr} 303 if req.callb.hasCtx { 304 arguments = append(arguments, reflect.ValueOf(ctx)) 305 } 306 if len(req.args) > 0 { 307 arguments = append(arguments, req.args...) 308 } 309 310 // execute RPC method and return result 311 reply := req.callb.method.Func.Call(arguments) 312 if len(reply) == 0 { 313 return codec.CreateResponse(req.id, nil), nil 314 } 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 { // eth_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.method, 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 }