server.go 14 KB

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