github.com/FUSIONFoundation/efsn@v3.6.2-0.20200916075423-dbb5dd5d2cc7+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  	"github.com/FusionFoundation/efsn/log"
    29  	mapset "github.com/deckarep/golang-set"
    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 ID, err 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  
   246  	defer func() {
   247  		if r := recover(); r != nil {
   248  			id = ""
   249  			err = fmt.Errorf("rpc callback panic: %v", r)
   250  		}
   251  	}()
   252  	reply := req.callb.method.Func.Call(args)
   253  
   254  	if !reply[1].IsNil() { // subscription creation failed
   255  		return "", reply[1].Interface().(error)
   256  	}
   257  
   258  	return reply[0].Interface().(*Subscription).ID, nil
   259  }
   260  
   261  // handle executes a request and returns the response from the callback.
   262  func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (response interface{}, callback func()) {
   263  	if req.err != nil {
   264  		return codec.CreateErrorResponse(&req.id, req.err), nil
   265  	}
   266  
   267  	if req.isUnsubscribe { // cancel subscription, first param must be the subscription id
   268  		if len(req.args) >= 1 && req.args[0].Kind() == reflect.String {
   269  			notifier, supported := NotifierFromContext(ctx)
   270  			if !supported { // interface doesn't support subscriptions (e.g. http)
   271  				return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil
   272  			}
   273  
   274  			subid := ID(req.args[0].String())
   275  			if err := notifier.unsubscribe(subid); err != nil {
   276  				return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
   277  			}
   278  
   279  			return codec.CreateResponse(req.id, true), nil
   280  		}
   281  		return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil
   282  	}
   283  
   284  	if req.callb.isSubscribe {
   285  		subid, err := s.createSubscription(ctx, codec, req)
   286  		if err != nil {
   287  			return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
   288  		}
   289  
   290  		// active the subscription after the sub id was successfully sent to the client
   291  		activateSub := func() {
   292  			notifier, _ := NotifierFromContext(ctx)
   293  			notifier.activate(subid, req.svcname)
   294  		}
   295  
   296  		return codec.CreateResponse(req.id, subid), activateSub
   297  	}
   298  
   299  	// regular RPC call, prepare arguments
   300  	if len(req.args) != len(req.callb.argTypes) {
   301  		rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d",
   302  			req.svcname, serviceMethodSeparator, req.callb.method.Name,
   303  			len(req.callb.argTypes), len(req.args))}
   304  		return codec.CreateErrorResponse(&req.id, rpcErr), nil
   305  	}
   306  
   307  	arguments := []reflect.Value{req.callb.rcvr}
   308  	if req.callb.hasCtx {
   309  		arguments = append(arguments, reflect.ValueOf(ctx))
   310  	}
   311  	if len(req.args) > 0 {
   312  		arguments = append(arguments, req.args...)
   313  	}
   314  
   315  	// execute RPC method and return result
   316  	defer func() {
   317  		if r := recover(); r != nil {
   318  			panicErr := fmt.Errorf("rpc callback panic: %v", r)
   319  			response = codec.CreateErrorResponse(&req.id, &callbackError{panicErr.Error()})
   320  			callback = nil
   321  		}
   322  	}()
   323  	reply := req.callb.method.Func.Call(arguments)
   324  	if len(reply) == 0 {
   325  		return codec.CreateResponse(req.id, nil), nil
   326  	}
   327  	if req.callb.errPos >= 0 { // test if method returned an error
   328  		if !reply[req.callb.errPos].IsNil() {
   329  			e := reply[req.callb.errPos].Interface().(error)
   330  			res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()})
   331  			return res, nil
   332  		}
   333  	}
   334  	return codec.CreateResponse(req.id, reply[0].Interface()), nil
   335  }
   336  
   337  // exec executes the given request and writes the result back using the codec.
   338  func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) {
   339  	var response interface{}
   340  	var callback func()
   341  	if req.err != nil {
   342  		response = codec.CreateErrorResponse(&req.id, req.err)
   343  	} else {
   344  		response, callback = s.handle(ctx, codec, req)
   345  	}
   346  
   347  	if err := codec.Write(response); err != nil {
   348  		log.Error(fmt.Sprintf("%v\n", err))
   349  		codec.Close()
   350  	}
   351  
   352  	// when request was a subscribe request this allows these subscriptions to be actived
   353  	if callback != nil {
   354  		callback()
   355  	}
   356  }
   357  
   358  // execBatch executes the given requests and writes the result back using the codec.
   359  // It will only write the response back when the last request is processed.
   360  func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) {
   361  	responses := make([]interface{}, len(requests))
   362  	var callbacks []func()
   363  	for i, req := range requests {
   364  		if req.err != nil {
   365  			responses[i] = codec.CreateErrorResponse(&req.id, req.err)
   366  		} else {
   367  			var callback func()
   368  			if responses[i], callback = s.handle(ctx, codec, req); callback != nil {
   369  				callbacks = append(callbacks, callback)
   370  			}
   371  		}
   372  	}
   373  
   374  	if err := codec.Write(responses); err != nil {
   375  		log.Error(fmt.Sprintf("%v\n", err))
   376  		codec.Close()
   377  	}
   378  
   379  	// when request holds one of more subscribe requests this allows these subscriptions to be activated
   380  	for _, c := range callbacks {
   381  		c()
   382  	}
   383  }
   384  
   385  // readRequest requests the next (batch) request from the codec. It will return the collection
   386  // of requests, an indication if the request was a batch, the invalid request identifier and an
   387  // error when the request could not be read/parsed.
   388  func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) {
   389  	reqs, batch, err := codec.ReadRequestHeaders()
   390  	if err != nil {
   391  		return nil, batch, err
   392  	}
   393  
   394  	requests := make([]*serverRequest, len(reqs))
   395  
   396  	// verify requests
   397  	for i, r := range reqs {
   398  		var ok bool
   399  		var svc *service
   400  
   401  		if r.err != nil {
   402  			requests[i] = &serverRequest{id: r.id, err: r.err}
   403  			continue
   404  		}
   405  
   406  		if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) {
   407  			requests[i] = &serverRequest{id: r.id, isUnsubscribe: true}
   408  			argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg
   409  			if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
   410  				requests[i].args = args
   411  			} else {
   412  				requests[i].err = &invalidParamsError{err.Error()}
   413  			}
   414  			continue
   415  		}
   416  
   417  		if svc, ok = s.services[r.service]; !ok { // rpc method isn't available
   418  			requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
   419  			continue
   420  		}
   421  
   422  		if r.isPubSub { // eth_subscribe, r.method contains the subscription method name
   423  			if callb, ok := svc.subscriptions[r.method]; ok {
   424  				requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
   425  				if r.params != nil && len(callb.argTypes) > 0 {
   426  					argTypes := []reflect.Type{reflect.TypeOf("")}
   427  					argTypes = append(argTypes, callb.argTypes...)
   428  					if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
   429  						requests[i].args = args[1:] // first one is service.method name which isn't an actual argument
   430  					} else {
   431  						requests[i].err = &invalidParamsError{err.Error()}
   432  					}
   433  				}
   434  			} else {
   435  				requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
   436  			}
   437  			continue
   438  		}
   439  
   440  		if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method
   441  			requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
   442  			if r.params != nil && len(callb.argTypes) > 0 {
   443  				if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil {
   444  					requests[i].args = args
   445  				} else {
   446  					requests[i].err = &invalidParamsError{err.Error()}
   447  				}
   448  			}
   449  			continue
   450  		}
   451  
   452  		requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
   453  	}
   454  
   455  	return requests, batch, nil
   456  }