server.go 15 KB

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