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