server.go 15 KB

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