server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 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: set.New(),
  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. // already a previous service register under given sname, merge methods/subscriptions
  81. if regsvc, present := s.services[name]; present {
  82. if len(methods) == 0 && len(subscriptions) == 0 {
  83. return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
  84. }
  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. if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 {
  96. return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
  97. }
  98. s.services[svc.name] = svc
  99. return nil
  100. }
  101. // serveRequest will reads requests from the codec, calls the RPC callback and
  102. // writes the response to the given codec.
  103. //
  104. // If singleShot is true it will process a single request, otherwise it will handle
  105. // requests until the codec returns an error when reading a request (in most cases
  106. // an EOF). It executes requests in parallel when singleShot is false.
  107. func (s *Server) serveRequest(ctx context.Context, codec ServerCodec, singleShot bool, options CodecOption) error {
  108. var pend sync.WaitGroup
  109. defer func() {
  110. if err := recover(); err != nil {
  111. const size = 64 << 10
  112. buf := make([]byte, size)
  113. buf = buf[:runtime.Stack(buf, false)]
  114. log.Error(string(buf))
  115. }
  116. s.codecsMu.Lock()
  117. s.codecs.Remove(codec)
  118. s.codecsMu.Unlock()
  119. }()
  120. // ctx, cancel := context.WithCancel(context.Background())
  121. ctx, cancel := context.WithCancel(ctx)
  122. defer cancel()
  123. // if the codec supports notification include a notifier that callbacks can use
  124. // to send notification to clients. It is thight to the codec/connection. If the
  125. // connection is closed the notifier will stop and cancels all active subscriptions.
  126. if options&OptionSubscriptions == OptionSubscriptions {
  127. ctx = context.WithValue(ctx, notifierKey{}, newNotifier(codec))
  128. }
  129. s.codecsMu.Lock()
  130. if atomic.LoadInt32(&s.run) != 1 { // server stopped
  131. s.codecsMu.Unlock()
  132. return &shutdownError{}
  133. }
  134. s.codecs.Add(codec)
  135. s.codecsMu.Unlock()
  136. // test if the server is ordered to stop
  137. for atomic.LoadInt32(&s.run) == 1 {
  138. reqs, batch, err := s.readRequest(codec)
  139. if err != nil {
  140. // If a parsing error occurred, send an error
  141. if err.Error() != "EOF" {
  142. log.Debug(fmt.Sprintf("read error %v\n", err))
  143. codec.Write(codec.CreateErrorResponse(nil, err))
  144. }
  145. // Error or end of stream, wait for requests and tear down
  146. pend.Wait()
  147. return nil
  148. }
  149. // check if server is ordered to shutdown and return an error
  150. // telling the client that his request failed.
  151. if atomic.LoadInt32(&s.run) != 1 {
  152. err = &shutdownError{}
  153. if batch {
  154. resps := make([]interface{}, len(reqs))
  155. for i, r := range reqs {
  156. resps[i] = codec.CreateErrorResponse(&r.id, err)
  157. }
  158. codec.Write(resps)
  159. } else {
  160. codec.Write(codec.CreateErrorResponse(&reqs[0].id, err))
  161. }
  162. return nil
  163. }
  164. // If a single shot request is executing, run and return immediately
  165. if singleShot {
  166. if batch {
  167. s.execBatch(ctx, codec, reqs)
  168. } else {
  169. s.exec(ctx, codec, reqs[0])
  170. }
  171. return nil
  172. }
  173. // For multi-shot connections, start a goroutine to serve and loop back
  174. pend.Add(1)
  175. go func(reqs []*serverRequest, batch bool) {
  176. defer pend.Done()
  177. if batch {
  178. s.execBatch(ctx, codec, reqs)
  179. } else {
  180. s.exec(ctx, codec, reqs[0])
  181. }
  182. }(reqs, batch)
  183. }
  184. return nil
  185. }
  186. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the
  187. // response back using the given codec. It will block until the codec is closed or the server is
  188. // stopped. In either case the codec is closed.
  189. func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
  190. defer codec.Close()
  191. s.serveRequest(context.Background(), codec, false, options)
  192. }
  193. // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not
  194. // close the codec unless a non-recoverable error has occurred. Note, this method will return after
  195. // a single request has been processed!
  196. func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec, options CodecOption) {
  197. s.serveRequest(ctx, codec, true, options)
  198. }
  199. // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish,
  200. // close all codecs which will cancel pending requests/subscriptions.
  201. func (s *Server) Stop() {
  202. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  203. log.Debug("RPC Server shutdown initiatied")
  204. s.codecsMu.Lock()
  205. defer s.codecsMu.Unlock()
  206. s.codecs.Each(func(c interface{}) bool {
  207. c.(ServerCodec).Close()
  208. return true
  209. })
  210. }
  211. }
  212. // createSubscription will call the subscription callback and returns the subscription id or error.
  213. func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) {
  214. // subscription have as first argument the context following optional arguments
  215. args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)}
  216. args = append(args, req.args...)
  217. reply := req.callb.method.Func.Call(args)
  218. if !reply[1].IsNil() { // subscription creation failed
  219. return "", reply[1].Interface().(error)
  220. }
  221. return reply[0].Interface().(*Subscription).ID, nil
  222. }
  223. // handle executes a request and returns the response from the callback.
  224. func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) {
  225. if req.err != nil {
  226. return codec.CreateErrorResponse(&req.id, req.err), nil
  227. }
  228. if req.isUnsubscribe { // cancel subscription, first param must be the subscription id
  229. if len(req.args) >= 1 && req.args[0].Kind() == reflect.String {
  230. notifier, supported := NotifierFromContext(ctx)
  231. if !supported { // interface doesn't support subscriptions (e.g. http)
  232. return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil
  233. }
  234. subid := ID(req.args[0].String())
  235. if err := notifier.unsubscribe(subid); err != nil {
  236. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
  237. }
  238. return codec.CreateResponse(req.id, true), nil
  239. }
  240. return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil
  241. }
  242. if req.callb.isSubscribe {
  243. subid, err := s.createSubscription(ctx, codec, req)
  244. if err != nil {
  245. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
  246. }
  247. // active the subscription after the sub id was successfully sent to the client
  248. activateSub := func() {
  249. notifier, _ := NotifierFromContext(ctx)
  250. notifier.activate(subid, req.svcname)
  251. }
  252. return codec.CreateResponse(req.id, subid), activateSub
  253. }
  254. // regular RPC call, prepare arguments
  255. if len(req.args) != len(req.callb.argTypes) {
  256. rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d",
  257. req.svcname, serviceMethodSeparator, req.callb.method.Name,
  258. len(req.callb.argTypes), len(req.args))}
  259. return codec.CreateErrorResponse(&req.id, rpcErr), nil
  260. }
  261. arguments := []reflect.Value{req.callb.rcvr}
  262. if req.callb.hasCtx {
  263. arguments = append(arguments, reflect.ValueOf(ctx))
  264. }
  265. if len(req.args) > 0 {
  266. arguments = append(arguments, req.args...)
  267. }
  268. // execute RPC method and return result
  269. reply := req.callb.method.Func.Call(arguments)
  270. if len(reply) == 0 {
  271. return codec.CreateResponse(req.id, nil), nil
  272. }
  273. if req.callb.errPos >= 0 { // test if method returned an error
  274. if !reply[req.callb.errPos].IsNil() {
  275. e := reply[req.callb.errPos].Interface().(error)
  276. res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()})
  277. return res, nil
  278. }
  279. }
  280. return codec.CreateResponse(req.id, reply[0].Interface()), nil
  281. }
  282. // exec executes the given request and writes the result back using the codec.
  283. func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) {
  284. var response interface{}
  285. var callback func()
  286. if req.err != nil {
  287. response = codec.CreateErrorResponse(&req.id, req.err)
  288. } else {
  289. response, callback = s.handle(ctx, codec, req)
  290. }
  291. if err := codec.Write(response); err != nil {
  292. log.Error(fmt.Sprintf("%v\n", err))
  293. codec.Close()
  294. }
  295. // when request was a subscribe request this allows these subscriptions to be actived
  296. if callback != nil {
  297. callback()
  298. }
  299. }
  300. // execBatch executes the given requests and writes the result back using the codec.
  301. // It will only write the response back when the last request is processed.
  302. func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) {
  303. responses := make([]interface{}, len(requests))
  304. var callbacks []func()
  305. for i, req := range requests {
  306. if req.err != nil {
  307. responses[i] = codec.CreateErrorResponse(&req.id, req.err)
  308. } else {
  309. var callback func()
  310. if responses[i], callback = s.handle(ctx, codec, req); callback != nil {
  311. callbacks = append(callbacks, callback)
  312. }
  313. }
  314. }
  315. if err := codec.Write(responses); err != nil {
  316. log.Error(fmt.Sprintf("%v\n", err))
  317. codec.Close()
  318. }
  319. // when request holds one of more subscribe requests this allows these subscriptions to be activated
  320. for _, c := range callbacks {
  321. c()
  322. }
  323. }
  324. // readRequest requests the next (batch) request from the codec. It will return the collection
  325. // of requests, an indication if the request was a batch, the invalid request identifier and an
  326. // error when the request could not be read/parsed.
  327. func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) {
  328. reqs, batch, err := codec.ReadRequestHeaders()
  329. if err != nil {
  330. return nil, batch, err
  331. }
  332. requests := make([]*serverRequest, len(reqs))
  333. // verify requests
  334. for i, r := range reqs {
  335. var ok bool
  336. var svc *service
  337. if r.err != nil {
  338. requests[i] = &serverRequest{id: r.id, err: r.err}
  339. continue
  340. }
  341. if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) {
  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{r.service, 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. }