server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/event"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "golang.org/x/net/context"
  27. "gopkg.in/fatih/set.v0"
  28. )
  29. const (
  30. stopPendingRequestTimeout = 3 * time.Second // give pending requests stopPendingRequestTimeout the time to finish when the server is stopped
  31. DefaultIPCApis = "admin,eth,debug,miner,net,shh,txpool,personal,web3"
  32. DefaultHTTPApis = "eth,net,web3"
  33. )
  34. // NewServer will create a new server instance with no registered handlers.
  35. func NewServer() *Server {
  36. server := &Server{
  37. services: make(serviceRegistry),
  38. subscriptions: make(subscriptionRegistry),
  39. codecs: set.New(),
  40. run: 1,
  41. }
  42. // register a default service which will provide meta information about the RPC service such as the services and
  43. // methods it offers.
  44. rpcService := &RPCService{server}
  45. server.RegisterName("rpc", rpcService)
  46. return server
  47. }
  48. // RPCService gives meta information about the server.
  49. // e.g. gives information about the loaded modules.
  50. type RPCService struct {
  51. server *Server
  52. }
  53. // Modules returns the list of RPC services with their version number
  54. func (s *RPCService) Modules() map[string]string {
  55. modules := make(map[string]string)
  56. for name, _ := range s.server.services {
  57. modules[name] = "1.0"
  58. }
  59. return modules
  60. }
  61. // RegisterName will create an service for the given rcvr type under the given name. When no methods on the given rcvr
  62. // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is
  63. // created and added to the service collection this server instance serves.
  64. func (s *Server) RegisterName(name string, rcvr interface{}) error {
  65. if s.services == nil {
  66. s.services = make(serviceRegistry)
  67. }
  68. svc := new(service)
  69. svc.typ = reflect.TypeOf(rcvr)
  70. rcvrVal := reflect.ValueOf(rcvr)
  71. if name == "" {
  72. return fmt.Errorf("no service name for type %s", svc.typ.String())
  73. }
  74. if !isExported(reflect.Indirect(rcvrVal).Type().Name()) {
  75. return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name())
  76. }
  77. // already a previous service register under given sname, merge methods/subscriptions
  78. if regsvc, present := s.services[name]; present {
  79. methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ)
  80. if len(methods) == 0 && len(subscriptions) == 0 {
  81. return fmt.Errorf("Service doesn't have any suitable methods/subscriptions to expose")
  82. }
  83. for _, m := range methods {
  84. regsvc.callbacks[formatName(m.method.Name)] = m
  85. }
  86. for _, s := range subscriptions {
  87. regsvc.subscriptions[formatName(s.method.Name)] = s
  88. }
  89. return nil
  90. }
  91. svc.name = name
  92. svc.callbacks, svc.subscriptions = suitableCallbacks(rcvrVal, svc.typ)
  93. if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 {
  94. return fmt.Errorf("Service doesn't have any suitable methods/subscriptions to expose")
  95. }
  96. s.services[svc.name] = svc
  97. return nil
  98. }
  99. // serveRequest will reads requests from the codec, calls the RPC callback and
  100. // writes the response to the given codec.
  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(codec ServerCodec, singleShot bool) error {
  105. defer func() {
  106. if err := recover(); err != nil {
  107. const size = 64 << 10
  108. buf := make([]byte, size)
  109. buf = buf[:runtime.Stack(buf, false)]
  110. glog.Errorln(string(buf))
  111. }
  112. s.codecsMu.Lock()
  113. s.codecs.Remove(codec)
  114. s.codecsMu.Unlock()
  115. return
  116. }()
  117. ctx, cancel := context.WithCancel(context.Background())
  118. defer cancel()
  119. s.codecsMu.Lock()
  120. if atomic.LoadInt32(&s.run) != 1 { // server stopped
  121. s.codecsMu.Unlock()
  122. return &shutdownError{}
  123. }
  124. s.codecs.Add(codec)
  125. s.codecsMu.Unlock()
  126. // test if the server is ordered to stop
  127. for atomic.LoadInt32(&s.run) == 1 {
  128. reqs, batch, err := s.readRequest(codec)
  129. if err != nil {
  130. glog.V(logger.Debug).Infof("%v\n", err)
  131. codec.Write(codec.CreateErrorResponse(nil, err))
  132. return nil
  133. }
  134. // check if server is ordered to shutdown and return an error
  135. // telling the client that his request failed.
  136. if atomic.LoadInt32(&s.run) != 1 {
  137. err = &shutdownError{}
  138. if batch {
  139. resps := make([]interface{}, len(reqs))
  140. for i, r := range reqs {
  141. resps[i] = codec.CreateErrorResponse(&r.id, err)
  142. }
  143. codec.Write(resps)
  144. } else {
  145. codec.Write(codec.CreateErrorResponse(&reqs[0].id, err))
  146. }
  147. return nil
  148. }
  149. if singleShot && batch {
  150. s.execBatch(ctx, codec, reqs)
  151. return nil
  152. } else if singleShot && !batch {
  153. s.exec(ctx, codec, reqs[0])
  154. return nil
  155. } else if !singleShot && batch {
  156. go s.execBatch(ctx, codec, reqs)
  157. } else {
  158. go s.exec(ctx, codec, reqs[0])
  159. }
  160. }
  161. return nil
  162. }
  163. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the
  164. // response back using the given codec. It will block until the codec is closed or the server is
  165. // stopped. In either case the codec is closed.
  166. //
  167. // This server will:
  168. // 1. allow for asynchronous and parallel request execution
  169. // 2. supports notifications (pub/sub)
  170. // 3. supports request batches
  171. func (s *Server) ServeCodec(codec ServerCodec) {
  172. defer codec.Close()
  173. s.serveRequest(codec, false)
  174. }
  175. // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not
  176. // close the codec unless a non-recoverable error has occurred.
  177. func (s *Server) ServeSingleRequest(codec ServerCodec) {
  178. s.serveRequest(codec, true)
  179. }
  180. // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish,
  181. // close all codecs which will cancels pending requests/subscriptions.
  182. func (s *Server) Stop() {
  183. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  184. glog.V(logger.Debug).Infoln("RPC Server shutdown initiatied")
  185. time.AfterFunc(stopPendingRequestTimeout, func() {
  186. s.codecsMu.Lock()
  187. defer s.codecsMu.Unlock()
  188. s.codecs.Each(func(c interface{}) bool {
  189. c.(ServerCodec).Close()
  190. return true
  191. })
  192. })
  193. }
  194. }
  195. // sendNotification will create a notification from the given event by serializing member fields of the event.
  196. // It will then send the notification to the client, when it fails the codec is closed. When the event has multiple
  197. // fields an array of values is returned.
  198. func sendNotification(codec ServerCodec, subid string, event interface{}) {
  199. notification := codec.CreateNotification(subid, event)
  200. if err := codec.Write(notification); err != nil {
  201. codec.Close()
  202. }
  203. }
  204. // createSubscription will register a new subscription and waits for raised events. When an event is raised it will:
  205. // 1. test if the event is raised matches the criteria the user has (optionally) specified
  206. // 2. create a notification of the event and send it the client when it matches the criteria
  207. // It will unsubscribe the subscription when the socket is closed or the subscription is unsubscribed by the user.
  208. func (s *Server) createSubscription(c ServerCodec, req *serverRequest) (string, error) {
  209. args := []reflect.Value{req.callb.rcvr}
  210. if len(req.args) > 0 {
  211. args = append(args, req.args...)
  212. }
  213. subid, err := newSubscriptionId()
  214. if err != nil {
  215. return "", err
  216. }
  217. reply := req.callb.method.Func.Call(args)
  218. if reply[1].IsNil() { // no error
  219. if subscription, ok := reply[0].Interface().(Subscription); ok {
  220. s.muSubcriptions.Lock()
  221. s.subscriptions[subid] = subscription
  222. s.muSubcriptions.Unlock()
  223. go func() {
  224. cases := []reflect.SelectCase{
  225. reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(subscription.Chan())}, // new event
  226. reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c.Closed())}, // connection closed
  227. }
  228. for {
  229. idx, notification, recvOk := reflect.Select(cases)
  230. switch idx {
  231. case 0: // new event, or channel closed
  232. if recvOk { // send notification
  233. if event, ok := notification.Interface().(*event.Event); ok {
  234. if subscription.match == nil || subscription.match(event.Data) {
  235. sendNotification(c, subid, subscription.format(event.Data))
  236. }
  237. }
  238. } else { // user send an eth_unsubscribe request
  239. return
  240. }
  241. case 1: // connection closed
  242. s.unsubscribe(subid)
  243. return
  244. }
  245. }
  246. }()
  247. } else { // unable to create subscription
  248. s.muSubcriptions.Lock()
  249. delete(s.subscriptions, subid)
  250. s.muSubcriptions.Unlock()
  251. }
  252. } else {
  253. return "", fmt.Errorf("Unable to create subscription")
  254. }
  255. return subid, nil
  256. }
  257. // unsubscribe calls the Unsubscribe method on the subscription and removes a subscription from the subscription
  258. // registry.
  259. func (s *Server) unsubscribe(subid string) bool {
  260. s.muSubcriptions.Lock()
  261. defer s.muSubcriptions.Unlock()
  262. if sub, ok := s.subscriptions[subid]; ok {
  263. sub.Unsubscribe()
  264. delete(s.subscriptions, subid)
  265. return true
  266. }
  267. return false
  268. }
  269. // handle executes a request and returns the response from the callback.
  270. func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) interface{} {
  271. if req.err != nil {
  272. return codec.CreateErrorResponse(&req.id, req.err)
  273. }
  274. if req.isUnsubscribe { // first param must be the subscription id
  275. if len(req.args) >= 1 && req.args[0].Kind() == reflect.String {
  276. subid := req.args[0].String()
  277. if s.unsubscribe(subid) {
  278. return codec.CreateResponse(req.id, true)
  279. } else {
  280. return codec.CreateErrorResponse(&req.id,
  281. &callbackError{fmt.Sprintf("subscription '%s' not found", subid)})
  282. }
  283. }
  284. return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as argument"})
  285. }
  286. if req.callb.isSubscribe {
  287. subid, err := s.createSubscription(codec, req)
  288. if err != nil {
  289. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()})
  290. }
  291. return codec.CreateResponse(req.id, subid)
  292. }
  293. // regular RPC call
  294. if len(req.args) != len(req.callb.argTypes) {
  295. rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d",
  296. req.svcname, serviceMethodSeparator, req.callb.method.Name,
  297. len(req.callb.argTypes), len(req.args))}
  298. return codec.CreateErrorResponse(&req.id, rpcErr)
  299. }
  300. arguments := []reflect.Value{req.callb.rcvr}
  301. if req.callb.hasCtx {
  302. arguments = append(arguments, reflect.ValueOf(ctx))
  303. }
  304. if len(req.args) > 0 {
  305. arguments = append(arguments, req.args...)
  306. }
  307. reply := req.callb.method.Func.Call(arguments)
  308. if len(reply) == 0 {
  309. return codec.CreateResponse(req.id, nil)
  310. }
  311. if req.callb.errPos >= 0 { // test if method returned an error
  312. if !reply[req.callb.errPos].IsNil() {
  313. e := reply[req.callb.errPos].Interface().(error)
  314. res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()})
  315. return res
  316. }
  317. }
  318. return codec.CreateResponse(req.id, reply[0].Interface())
  319. }
  320. // exec executes the given request and writes the result back using the codec.
  321. func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) {
  322. var response interface{}
  323. if req.err != nil {
  324. response = codec.CreateErrorResponse(&req.id, req.err)
  325. } else {
  326. response = s.handle(ctx, codec, req)
  327. }
  328. if err := codec.Write(response); err != nil {
  329. glog.V(logger.Error).Infof("%v\n", err)
  330. codec.Close()
  331. }
  332. }
  333. // execBatch executes the given requests and writes the result back using the codec. It will only write the response
  334. // back when the last request is processed.
  335. func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) {
  336. responses := make([]interface{}, len(requests))
  337. for i, req := range requests {
  338. if req.err != nil {
  339. responses[i] = codec.CreateErrorResponse(&req.id, req.err)
  340. } else {
  341. responses[i] = s.handle(ctx, codec, req)
  342. }
  343. }
  344. if err := codec.Write(responses); err != nil {
  345. glog.V(logger.Error).Infof("%v\n", err)
  346. codec.Close()
  347. }
  348. }
  349. // readRequest requests the next (batch) request from the codec. It will return the collection of requests, an
  350. // indication if the request was a batch, the invalid request identifier and an error when the request could not be
  351. // read/parsed.
  352. func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, RPCError) {
  353. reqs, batch, err := codec.ReadRequestHeaders()
  354. if err != nil {
  355. return nil, batch, err
  356. }
  357. requests := make([]*serverRequest, len(reqs))
  358. // verify requests
  359. for i, r := range reqs {
  360. var ok bool
  361. var svc *service
  362. if r.isPubSub && r.method == unsubscribeMethod {
  363. requests[i] = &serverRequest{id: r.id, isUnsubscribe: true}
  364. argTypes := []reflect.Type{reflect.TypeOf("")}
  365. if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
  366. requests[i].args = args
  367. } else {
  368. requests[i].err = &invalidParamsError{err.Error()}
  369. }
  370. continue
  371. }
  372. if svc, ok = s.services[r.service]; !ok {
  373. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
  374. continue
  375. }
  376. if r.isPubSub { // eth_subscribe
  377. if callb, ok := svc.subscriptions[r.method]; ok {
  378. requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
  379. if r.params != nil && len(callb.argTypes) > 0 {
  380. argTypes := []reflect.Type{reflect.TypeOf("")}
  381. argTypes = append(argTypes, callb.argTypes...)
  382. if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
  383. requests[i].args = args[1:] // first one is service.method name which isn't an actual argument
  384. } else {
  385. requests[i].err = &invalidParamsError{err.Error()}
  386. }
  387. }
  388. } else {
  389. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{subscribeMethod, r.method}}
  390. }
  391. continue
  392. }
  393. if callb, ok := svc.callbacks[r.method]; ok {
  394. requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
  395. if r.params != nil && len(callb.argTypes) > 0 {
  396. if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil {
  397. requests[i].args = args
  398. } else {
  399. requests[i].err = &invalidParamsError{err.Error()}
  400. }
  401. }
  402. continue
  403. }
  404. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
  405. }
  406. return requests, batch, nil
  407. }