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