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