github.com/ethereumproject/go-ethereum@v5.5.2+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  	"sync"
    25  	"sync/atomic"
    26  	"time"
    27  
    28  	"gopkg.in/fatih/set.v0"
    29  
    30  	"github.com/ethereumproject/go-ethereum/logger"
    31  	"github.com/ethereumproject/go-ethereum/logger/glog"
    32  )
    33  
    34  const (
    35  	stopPendingRequestTimeout = 3 * time.Second // give pending requests stopPendingRequestTimeout the time to finish when the server is stopped
    36  
    37  	notificationBufferSize = 10000 // max buffered notifications before codec is closed
    38  
    39  	MetadataApi     = "rpc"
    40  	DefaultIPCApis  = "admin,debug,eth,miner,net,personal,shh,txpool,web3,geth"
    41  	DefaultHTTPApis = "eth,net,web3"
    42  )
    43  
    44  // CodecOption specifies which type of messages this codec supports
    45  type CodecOption int
    46  
    47  const (
    48  	// OptionMethodInvocation is an indication that the codec supports RPC method calls
    49  	OptionMethodInvocation CodecOption = 1 << iota
    50  
    51  	// OptionSubscriptions is an indication that the codec suports RPC notifications
    52  	OptionSubscriptions = 1 << iota // support pub sub
    53  )
    54  
    55  // NewServer will create a new server instance with no registered handlers.
    56  func NewServer() *Server {
    57  	server := &Server{
    58  		services:      make(serviceRegistry),
    59  		subscriptions: make(subscriptionRegistry),
    60  		codecs:        set.New(),
    61  		run:           1,
    62  	}
    63  
    64  	// register a default service which will provide meta information about the RPC service such as the services and
    65  	// methods it offers.
    66  	rpcService := &RPCService{server}
    67  	server.RegisterName(MetadataApi, rpcService)
    68  
    69  	return server
    70  }
    71  
    72  // RPCService gives meta information about the server.
    73  // e.g. gives information about the loaded modules.
    74  type RPCService struct {
    75  	server *Server
    76  }
    77  
    78  // Modules returns the list of RPC services with their version number
    79  func (s *RPCService) Modules() map[string]string {
    80  	modules := make(map[string]string)
    81  	for name := range s.server.services {
    82  		modules[name] = "1.0"
    83  	}
    84  	return modules
    85  }
    86  
    87  // RegisterName will create an service for the given rcvr type under the given name. When no methods on the given rcvr
    88  // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is
    89  // created and added to the service collection this server instance serves.
    90  func (s *Server) RegisterName(name string, rcvr interface{}) error {
    91  	if s.services == nil {
    92  		s.services = make(serviceRegistry)
    93  	}
    94  
    95  	svc := new(service)
    96  	svc.typ = reflect.TypeOf(rcvr)
    97  	rcvrVal := reflect.ValueOf(rcvr)
    98  
    99  	if name == "" {
   100  		return fmt.Errorf("no service name for type %s", svc.typ.String())
   101  	}
   102  	if !isExported(reflect.Indirect(rcvrVal).Type().Name()) {
   103  		return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name())
   104  	}
   105  
   106  	// already a previous service register under given sname, merge methods/subscriptions
   107  	if regsvc, present := s.services[name]; present {
   108  		methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ)
   109  		if len(methods) == 0 && len(subscriptions) == 0 {
   110  			return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
   111  		}
   112  
   113  		for _, m := range methods {
   114  			regsvc.callbacks[formatName(m.method.Name)] = m
   115  		}
   116  		for _, s := range subscriptions {
   117  			regsvc.subscriptions[formatName(s.method.Name)] = s
   118  		}
   119  
   120  		return nil
   121  	}
   122  
   123  	svc.name = name
   124  	svc.callbacks, svc.subscriptions = suitableCallbacks(rcvrVal, svc.typ)
   125  
   126  	if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 {
   127  		return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
   128  	}
   129  
   130  	s.services[svc.name] = svc
   131  
   132  	return nil
   133  }
   134  
   135  // serveRequest will reads requests from the codec, calls the RPC callback and
   136  // writes the response to the given codec.
   137  //
   138  // If singleShot is true it will process a single request, otherwise it will handle
   139  // requests until the codec returns an error when reading a request (in most cases
   140  // an EOF). It executes requests in parallel when singleShot is false.
   141  func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecOption) error {
   142  	var pend sync.WaitGroup
   143  
   144  	defer func() {
   145  		if err := recover(); err != nil {
   146  			const size = 64 << 10
   147  			buf := make([]byte, size)
   148  			buf = buf[:runtime.Stack(buf, false)]
   149  			glog.Errorln(string(buf))
   150  		}
   151  		s.codecsMu.Lock()
   152  		s.codecs.Remove(codec)
   153  		s.codecsMu.Unlock()
   154  
   155  		return
   156  	}()
   157  
   158  	ctx, cancel := context.WithCancel(context.Background())
   159  	defer cancel()
   160  
   161  	// if the codec supports notification include a notifier that callbacks can use
   162  	// to send notification to clients. It is thight to the codec/connection. If the
   163  	// connection is closed the notifier will stop and cancels all active subscriptions.
   164  	if options&OptionSubscriptions == OptionSubscriptions {
   165  		ctx = context.WithValue(ctx, notifierKey{}, newBufferedNotifier(codec, notificationBufferSize))
   166  	}
   167  	s.codecsMu.Lock()
   168  	if atomic.LoadInt32(&s.run) != 1 { // server stopped
   169  		s.codecsMu.Unlock()
   170  		return &shutdownError{}
   171  	}
   172  	s.codecs.Add(codec)
   173  	s.codecsMu.Unlock()
   174  
   175  	// test if the server is ordered to stop
   176  	for atomic.LoadInt32(&s.run) == 1 {
   177  		reqs, batch, err := s.readRequest(codec)
   178  		if err != nil {
   179  			// If a parsing error occurred, send an error
   180  			if err.Error() != "EOF" {
   181  				glog.V(logger.Debug).Infof("%v", err)
   182  				codec.Write(codec.CreateErrorResponse(nil, err))
   183  			}
   184  			// Error or end of stream, wait for requests and tear down
   185  			pend.Wait()
   186  			return nil
   187  		}
   188  
   189  		// check if server is ordered to shutdown and return an error
   190  		// telling the client that his request failed.
   191  		if atomic.LoadInt32(&s.run) != 1 {
   192  			err = &shutdownError{}
   193  			if batch {
   194  				resps := make([]interface{}, len(reqs))
   195  				for i, r := range reqs {
   196  					resps[i] = codec.CreateErrorResponse(&r.id, err)
   197  				}
   198  				codec.Write(resps)
   199  			} else {
   200  				codec.Write(codec.CreateErrorResponse(&reqs[0].id, err))
   201  			}
   202  			return nil
   203  		}
   204  		// If a single shot request is executing, run and return immediately
   205  		if singleShot {
   206  			if batch {
   207  				s.execBatch(ctx, codec, reqs)
   208  			} else {
   209  				s.exec(ctx, codec, reqs[0])
   210  			}
   211  			return nil
   212  		}
   213  		// For multi-shot connections, start a goroutine to serve and loop back
   214  		pend.Add(1)
   215  
   216  		go func(reqs []*serverRequest, batch bool) {
   217  			defer pend.Done()
   218  			if batch {
   219  				s.execBatch(ctx, codec, reqs)
   220  			} else {
   221  				s.exec(ctx, codec, reqs[0])
   222  			}
   223  		}(reqs, batch)
   224  	}
   225  	return nil
   226  }
   227  
   228  // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the
   229  // response back using the given codec. It will block until the codec is closed or the server is
   230  // stopped. In either case the codec is closed.
   231  func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
   232  	defer codec.Close()
   233  	s.serveRequest(codec, false, options)
   234  }
   235  
   236  // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not
   237  // close the codec unless a non-recoverable error has occurred. Note, this method will return after
   238  // a single request has been processed!
   239  func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption) {
   240  	s.serveRequest(codec, true, options)
   241  }
   242  
   243  // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish,
   244  // close all codecs which will cancels pending requests/subscriptions.
   245  func (s *Server) Stop() {
   246  	if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
   247  		glog.V(logger.Debug).Infoln("RPC Server shutdown initiatied")
   248  		time.AfterFunc(stopPendingRequestTimeout, func() {
   249  			s.codecsMu.Lock()
   250  			defer s.codecsMu.Unlock()
   251  			s.codecs.Each(func(c interface{}) bool {
   252  				c.(ServerCodec).Close()
   253  				return true
   254  			})
   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) (string, 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 := 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 successful sent to the client
   303  		activateSub := func() {
   304  			notifier, _ := NotifierFromContext(ctx)
   305  			notifier.(*bufferedNotifier).activate(subid)
   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  		glog.V(logger.Error).Infof("%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  		glog.V(logger.Error).Infof("%v\n", err)
   382  		codec.Close()
   383  	}
   384  
   385  	// when request holds one of more subscribe requests this allows these subscriptions to be actived
   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, RPCError) {
   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.isPubSub && r.method == unsubscribeMethod {
   408  			requests[i] = &serverRequest{id: r.id, isUnsubscribe: true}
   409  			argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg
   410  			if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
   411  				requests[i].args = args
   412  			} else {
   413  				requests[i].err = &invalidParamsError{err.Error()}
   414  			}
   415  			continue
   416  		}
   417  
   418  		if svc, ok = s.services[r.service]; !ok { // rpc method isn't available
   419  			requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
   420  			continue
   421  		}
   422  
   423  		if r.isPubSub { // eth_subscribe, r.method contains the subscription method name
   424  			if callb, ok := svc.subscriptions[r.method]; ok {
   425  				requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
   426  				if r.params != nil && len(callb.argTypes) > 0 {
   427  					argTypes := []reflect.Type{reflect.TypeOf("")}
   428  					argTypes = append(argTypes, callb.argTypes...)
   429  					if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
   430  						requests[i].args = args[1:] // first one is service.method name which isn't an actual argument
   431  					} else {
   432  						requests[i].err = &invalidParamsError{err.Error()}
   433  					}
   434  				}
   435  			} else {
   436  				requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{subscribeMethod, r.method}}
   437  			}
   438  			continue
   439  		}
   440  
   441  		if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method
   442  			requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
   443  			if r.params != nil && len(callb.argTypes) > 0 {
   444  				if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil {
   445  					requests[i].args = args
   446  				} else {
   447  					requests[i].err = &invalidParamsError{err.Error()}
   448  				}
   449  			}
   450  			continue
   451  		}
   452  
   453  		requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
   454  	}
   455  
   456  	return requests, batch, nil
   457  }