server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. "fmt"
  19. "reflect"
  20. "runtime"
  21. "sync/atomic"
  22. "time"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "golang.org/x/net/context"
  26. "gopkg.in/fatih/set.v0"
  27. )
  28. const (
  29. stopPendingRequestTimeout = 3 * time.Second // give pending requests stopPendingRequestTimeout the time to finish when the server is stopped
  30. notificationBufferSize = 10000 // max buffered notifications before codec is closed
  31. DefaultIPCApis = "admin,eth,debug,miner,net,shh,txpool,personal,web3"
  32. DefaultHTTPApis = "eth,net,web3"
  33. )
  34. // CodecOption specifies which type of messages this codec supports
  35. type CodecOption int
  36. const (
  37. // OptionMethodInvocation is an indication that the codec supports RPC method calls
  38. OptionMethodInvocation CodecOption = 1 << iota
  39. // OptionSubscriptions is an indication that the codec suports RPC notifications
  40. OptionSubscriptions = 1 << iota // support pub sub
  41. )
  42. // NewServer will create a new server instance with no registered handlers.
  43. func NewServer() *Server {
  44. server := &Server{
  45. services: make(serviceRegistry),
  46. subscriptions: make(subscriptionRegistry),
  47. codecs: set.New(),
  48. run: 1,
  49. }
  50. // register a default service which will provide meta information about the RPC service such as the services and
  51. // methods it offers.
  52. rpcService := &RPCService{server}
  53. server.RegisterName("rpc", rpcService)
  54. return server
  55. }
  56. // RPCService gives meta information about the server.
  57. // e.g. gives information about the loaded modules.
  58. type RPCService struct {
  59. server *Server
  60. }
  61. // Modules returns the list of RPC services with their version number
  62. func (s *RPCService) Modules() map[string]string {
  63. modules := make(map[string]string)
  64. for name := range s.server.services {
  65. modules[name] = "1.0"
  66. }
  67. return modules
  68. }
  69. // RegisterName will create an service for the given rcvr type under the given name. When no methods on the given rcvr
  70. // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is
  71. // created and added to the service collection this server instance serves.
  72. func (s *Server) RegisterName(name string, rcvr interface{}) error {
  73. if s.services == nil {
  74. s.services = make(serviceRegistry)
  75. }
  76. svc := new(service)
  77. svc.typ = reflect.TypeOf(rcvr)
  78. rcvrVal := reflect.ValueOf(rcvr)
  79. if name == "" {
  80. return fmt.Errorf("no service name for type %s", svc.typ.String())
  81. }
  82. if !isExported(reflect.Indirect(rcvrVal).Type().Name()) {
  83. return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name())
  84. }
  85. // already a previous service register under given sname, merge methods/subscriptions
  86. if regsvc, present := s.services[name]; present {
  87. methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ)
  88. if len(methods) == 0 && len(subscriptions) == 0 {
  89. return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
  90. }
  91. for _, m := range methods {
  92. regsvc.callbacks[formatName(m.method.Name)] = m
  93. }
  94. for _, s := range subscriptions {
  95. regsvc.subscriptions[formatName(s.method.Name)] = s
  96. }
  97. return nil
  98. }
  99. svc.name = name
  100. svc.callbacks, svc.subscriptions = suitableCallbacks(rcvrVal, svc.typ)
  101. if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 {
  102. return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr)
  103. }
  104. s.services[svc.name] = svc
  105. return nil
  106. }
  107. // hasOption returns true if option is included in options, otherwise false
  108. func hasOption(option CodecOption, options []CodecOption) bool {
  109. for _, o := range options {
  110. if option == o {
  111. return true
  112. }
  113. }
  114. return false
  115. }
  116. // serveRequest will reads requests from the codec, calls the RPC callback and
  117. // writes the response to the given codec.
  118. //
  119. // If singleShot is true it will process a single request, otherwise it will handle
  120. // requests until the codec returns an error when reading a request (in most cases
  121. // an EOF). It executes requests in parallel when singleShot is false.
  122. func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecOption) error {
  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. glog.Errorln(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{}, newBufferedNotifier(codec, notificationBufferSize))
  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. glog.V(logger.Debug).Infof("%v\n", err)
  155. codec.Write(codec.CreateErrorResponse(nil, err))
  156. return nil
  157. }
  158. // check if server is ordered to shutdown and return an error
  159. // telling the client that his request failed.
  160. if atomic.LoadInt32(&s.run) != 1 {
  161. err = &shutdownError{}
  162. if batch {
  163. resps := make([]interface{}, len(reqs))
  164. for i, r := range reqs {
  165. resps[i] = codec.CreateErrorResponse(&r.id, err)
  166. }
  167. codec.Write(resps)
  168. } else {
  169. codec.Write(codec.CreateErrorResponse(&reqs[0].id, err))
  170. }
  171. return nil
  172. }
  173. if singleShot && batch {
  174. s.execBatch(ctx, codec, reqs)
  175. return nil
  176. } else if singleShot && !batch {
  177. s.exec(ctx, codec, reqs[0])
  178. return nil
  179. } else if !singleShot && batch {
  180. go s.execBatch(ctx, codec, reqs)
  181. } else {
  182. go s.exec(ctx, codec, reqs[0])
  183. }
  184. }
  185. return nil
  186. }
  187. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the
  188. // response back using the given codec. It will block until the codec is closed or the server is
  189. // stopped. In either case the codec is closed.
  190. func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
  191. defer codec.Close()
  192. s.serveRequest(codec, false, options)
  193. }
  194. // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not
  195. // close the codec unless a non-recoverable error has occurred. Note, this method will return after
  196. // a single request has been processed!
  197. func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption) {
  198. s.serveRequest(codec, true, options)
  199. }
  200. // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish,
  201. // close all codecs which will cancels pending requests/subscriptions.
  202. func (s *Server) Stop() {
  203. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  204. glog.V(logger.Debug).Infoln("RPC Server shutdown initiatied")
  205. time.AfterFunc(stopPendingRequestTimeout, func() {
  206. s.codecsMu.Lock()
  207. defer s.codecsMu.Unlock()
  208. s.codecs.Each(func(c interface{}) bool {
  209. c.(ServerCodec).Close()
  210. return true
  211. })
  212. })
  213. }
  214. }
  215. // createSubscription will call the subscription callback and returns the subscription id or error.
  216. func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (string, error) {
  217. // subscription have as first argument the context following optional arguments
  218. args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)}
  219. args = append(args, req.args...)
  220. reply := req.callb.method.Func.Call(args)
  221. if !reply[1].IsNil() { // subscription creation failed
  222. return "", reply[1].Interface().(error)
  223. }
  224. return reply[0].Interface().(Subscription).ID(), nil
  225. }
  226. // handle executes a request and returns the response from the callback.
  227. func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) {
  228. if req.err != nil {
  229. return codec.CreateErrorResponse(&req.id, req.err), nil
  230. }
  231. if req.isUnsubscribe { // cancel subscription, first param must be the subscription id
  232. if len(req.args) >= 1 && req.args[0].Kind() == reflect.String {
  233. notifier, supported := NotifierFromContext(ctx)
  234. if !supported { // interface doesn't support subscriptions (e.g. http)
  235. return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil
  236. }
  237. subid := req.args[0].String()
  238. if err := notifier.Unsubscribe(subid); err != nil {
  239. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
  240. }
  241. return codec.CreateResponse(req.id, true), nil
  242. }
  243. return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil
  244. }
  245. if req.callb.isSubscribe {
  246. subid, err := s.createSubscription(ctx, codec, req)
  247. if err != nil {
  248. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil
  249. }
  250. // active the subscription after the sub id was successful sent to the client
  251. activateSub := func() {
  252. notifier, _ := NotifierFromContext(ctx)
  253. notifier.(*bufferedNotifier).activate(subid)
  254. }
  255. return codec.CreateResponse(req.id, subid), activateSub
  256. }
  257. // regular RPC call, prepare arguments
  258. if len(req.args) != len(req.callb.argTypes) {
  259. rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d",
  260. req.svcname, serviceMethodSeparator, req.callb.method.Name,
  261. len(req.callb.argTypes), len(req.args))}
  262. return codec.CreateErrorResponse(&req.id, rpcErr), nil
  263. }
  264. arguments := []reflect.Value{req.callb.rcvr}
  265. if req.callb.hasCtx {
  266. arguments = append(arguments, reflect.ValueOf(ctx))
  267. }
  268. if len(req.args) > 0 {
  269. arguments = append(arguments, req.args...)
  270. }
  271. // execute RPC method and return result
  272. reply := req.callb.method.Func.Call(arguments)
  273. if len(reply) == 0 {
  274. return codec.CreateResponse(req.id, nil), nil
  275. }
  276. if req.callb.errPos >= 0 { // test if method returned an error
  277. if !reply[req.callb.errPos].IsNil() {
  278. e := reply[req.callb.errPos].Interface().(error)
  279. res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()})
  280. return res, nil
  281. }
  282. }
  283. return codec.CreateResponse(req.id, reply[0].Interface()), nil
  284. }
  285. // exec executes the given request and writes the result back using the codec.
  286. func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) {
  287. var response interface{}
  288. var callback func()
  289. if req.err != nil {
  290. response = codec.CreateErrorResponse(&req.id, req.err)
  291. } else {
  292. response, callback = s.handle(ctx, codec, req)
  293. }
  294. if err := codec.Write(response); err != nil {
  295. glog.V(logger.Error).Infof("%v\n", err)
  296. codec.Close()
  297. }
  298. // when request was a subscribe request this allows these subscriptions to be actived
  299. if callback != nil {
  300. callback()
  301. }
  302. }
  303. // execBatch executes the given requests and writes the result back using the codec.
  304. // It will only write the response back when the last request is processed.
  305. func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) {
  306. responses := make([]interface{}, len(requests))
  307. var callbacks []func()
  308. for i, req := range requests {
  309. if req.err != nil {
  310. responses[i] = codec.CreateErrorResponse(&req.id, req.err)
  311. } else {
  312. var callback func()
  313. if responses[i], callback = s.handle(ctx, codec, req); callback != nil {
  314. callbacks = append(callbacks, callback)
  315. }
  316. }
  317. }
  318. if err := codec.Write(responses); err != nil {
  319. glog.V(logger.Error).Infof("%v\n", err)
  320. codec.Close()
  321. }
  322. // when request holds one of more subscribe requests this allows these subscriptions to be actived
  323. for _, c := range callbacks {
  324. c()
  325. }
  326. }
  327. // readRequest requests the next (batch) request from the codec. It will return the collection
  328. // of requests, an indication if the request was a batch, the invalid request identifier and an
  329. // error when the request could not be read/parsed.
  330. func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, RPCError) {
  331. reqs, batch, err := codec.ReadRequestHeaders()
  332. if err != nil {
  333. return nil, batch, err
  334. }
  335. requests := make([]*serverRequest, len(reqs))
  336. // verify requests
  337. for i, r := range reqs {
  338. var ok bool
  339. var svc *service
  340. if r.isPubSub && r.method == unsubscribeMethod {
  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{subscribeMethod, 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. }