server.go 14 KB

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