server.go 15 KB

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