server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. DefaultHttpRpcApis = "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. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the
  100. // response back using the given codec. It will block until the codec is closed.
  101. //
  102. // This server will:
  103. // 1. allow for asynchronous and parallel request execution
  104. // 2. supports notifications (pub/sub)
  105. // 3. supports request batches
  106. func (s *Server) ServeCodec(codec ServerCodec) {
  107. defer func() {
  108. if err := recover(); err != nil {
  109. const size = 64 << 10
  110. buf := make([]byte, size)
  111. buf = buf[:runtime.Stack(buf, false)]
  112. glog.Errorln(string(buf))
  113. }
  114. codec.Close()
  115. }()
  116. ctx, cancel := context.WithCancel(context.Background())
  117. defer cancel()
  118. s.codecsMu.Lock()
  119. if atomic.LoadInt32(&s.run) != 1 { // server stopped
  120. s.codecsMu.Unlock()
  121. return
  122. }
  123. s.codecs.Add(codec)
  124. s.codecsMu.Unlock()
  125. for atomic.LoadInt32(&s.run) == 1 {
  126. reqs, batch, err := s.readRequest(codec)
  127. if err != nil {
  128. glog.V(logger.Debug).Infof("%v\n", err)
  129. codec.Write(codec.CreateErrorResponse(nil, err))
  130. break
  131. }
  132. if atomic.LoadInt32(&s.run) != 1 {
  133. err = &shutdownError{}
  134. if batch {
  135. resps := make([]interface{}, len(reqs))
  136. for i, r := range reqs {
  137. resps[i] = codec.CreateErrorResponse(&r.id, err)
  138. }
  139. codec.Write(resps)
  140. } else {
  141. codec.Write(codec.CreateErrorResponse(&reqs[0].id, err))
  142. }
  143. break
  144. }
  145. if batch {
  146. go s.execBatch(ctx, codec, reqs)
  147. } else {
  148. go s.exec(ctx, codec, reqs[0])
  149. }
  150. }
  151. }
  152. // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish,
  153. // close all codecs which will cancels pending requests/subscriptions.
  154. func (s *Server) Stop() {
  155. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  156. glog.V(logger.Debug).Infoln("RPC Server shutdown initiatied")
  157. time.AfterFunc(stopPendingRequestTimeout, func() {
  158. s.codecsMu.Lock()
  159. defer s.codecsMu.Unlock()
  160. s.codecs.Each(func(c interface{}) bool {
  161. c.(ServerCodec).Close()
  162. return true
  163. })
  164. })
  165. }
  166. }
  167. // sendNotification will create a notification from the given event by serializing member fields of the event.
  168. // It will then send the notification to the client, when it fails the codec is closed. When the event has multiple
  169. // fields an array of values is returned.
  170. func sendNotification(codec ServerCodec, subid string, event interface{}) {
  171. notification := codec.CreateNotification(subid, event)
  172. if err := codec.Write(notification); err != nil {
  173. codec.Close()
  174. }
  175. }
  176. // createSubscription will register a new subscription and waits for raised events. When an event is raised it will:
  177. // 1. test if the event is raised matches the criteria the user has (optionally) specified
  178. // 2. create a notification of the event and send it the client when it matches the criteria
  179. // It will unsubscribe the subscription when the socket is closed or the subscription is unsubscribed by the user.
  180. func (s *Server) createSubscription(c ServerCodec, req *serverRequest) (string, error) {
  181. args := []reflect.Value{req.callb.rcvr}
  182. if len(req.args) > 0 {
  183. args = append(args, req.args...)
  184. }
  185. subid, err := newSubscriptionId()
  186. if err != nil {
  187. return "", err
  188. }
  189. reply := req.callb.method.Func.Call(args)
  190. if reply[1].IsNil() { // no error
  191. if subscription, ok := reply[0].Interface().(Subscription); ok {
  192. s.muSubcriptions.Lock()
  193. s.subscriptions[subid] = subscription
  194. s.muSubcriptions.Unlock()
  195. go func() {
  196. cases := []reflect.SelectCase{
  197. reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(subscription.Chan())}, // new event
  198. reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c.Closed())}, // connection closed
  199. }
  200. for {
  201. idx, notification, recvOk := reflect.Select(cases)
  202. switch idx {
  203. case 0: // new event, or channel closed
  204. if recvOk { // send notification
  205. if event, ok := notification.Interface().(*event.Event); ok {
  206. if subscription.match == nil || subscription.match(event.Data) {
  207. sendNotification(c, subid, subscription.format(event.Data))
  208. }
  209. }
  210. } else { // user send an eth_unsubscribe request
  211. return
  212. }
  213. case 1: // connection closed
  214. s.unsubscribe(subid)
  215. return
  216. }
  217. }
  218. }()
  219. } else { // unable to create subscription
  220. s.muSubcriptions.Lock()
  221. delete(s.subscriptions, subid)
  222. s.muSubcriptions.Unlock()
  223. }
  224. } else {
  225. return "", fmt.Errorf("Unable to create subscription")
  226. }
  227. return subid, nil
  228. }
  229. // unsubscribe calls the Unsubscribe method on the subscription and removes a subscription from the subscription
  230. // registry.
  231. func (s *Server) unsubscribe(subid string) bool {
  232. s.muSubcriptions.Lock()
  233. defer s.muSubcriptions.Unlock()
  234. if sub, ok := s.subscriptions[subid]; ok {
  235. sub.Unsubscribe()
  236. delete(s.subscriptions, subid)
  237. return true
  238. }
  239. return false
  240. }
  241. // handle executes a request and returns the response from the callback.
  242. func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) interface{} {
  243. if req.err != nil {
  244. return codec.CreateErrorResponse(&req.id, req.err)
  245. }
  246. if req.isUnsubscribe { // first param must be the subscription id
  247. if len(req.args) >= 1 && req.args[0].Kind() == reflect.String {
  248. subid := req.args[0].String()
  249. if s.unsubscribe(subid) {
  250. return codec.CreateResponse(req.id, true)
  251. } else {
  252. return codec.CreateErrorResponse(&req.id,
  253. &callbackError{fmt.Sprintf("subscription '%s' not found", subid)})
  254. }
  255. }
  256. return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as argument"})
  257. }
  258. if req.callb.isSubscribe {
  259. subid, err := s.createSubscription(codec, req)
  260. if err != nil {
  261. return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()})
  262. }
  263. return codec.CreateResponse(req.id, subid)
  264. }
  265. // regular RPC call
  266. if len(req.args) != len(req.callb.argTypes) {
  267. rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d",
  268. req.svcname, serviceMethodSeparator, req.callb.method.Name,
  269. len(req.callb.argTypes), len(req.args))}
  270. return codec.CreateErrorResponse(&req.id, rpcErr)
  271. }
  272. arguments := []reflect.Value{req.callb.rcvr}
  273. if req.callb.hasCtx {
  274. arguments = append(arguments, reflect.ValueOf(ctx))
  275. }
  276. if len(req.args) > 0 {
  277. arguments = append(arguments, req.args...)
  278. }
  279. reply := req.callb.method.Func.Call(arguments)
  280. if len(reply) == 0 {
  281. return codec.CreateResponse(req.id, nil)
  282. }
  283. if req.callb.errPos >= 0 { // test if method returned an error
  284. if !reply[req.callb.errPos].IsNil() {
  285. e := reply[req.callb.errPos].Interface().(error)
  286. res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()})
  287. return res
  288. }
  289. }
  290. return codec.CreateResponse(req.id, reply[0].Interface())
  291. }
  292. // exec executes the given request and writes the result back using the codec.
  293. func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) {
  294. var response interface{}
  295. if req.err != nil {
  296. response = codec.CreateErrorResponse(&req.id, req.err)
  297. } else {
  298. response = s.handle(ctx, codec, req)
  299. }
  300. if err := codec.Write(response); err != nil {
  301. glog.V(logger.Error).Infof("%v\n", err)
  302. codec.Close()
  303. }
  304. }
  305. // execBatch executes the given requests and writes the result back using the codec. It will only write the response
  306. // back when the last request is processed.
  307. func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) {
  308. responses := make([]interface{}, len(requests))
  309. for i, req := range requests {
  310. if req.err != nil {
  311. responses[i] = codec.CreateErrorResponse(&req.id, req.err)
  312. } else {
  313. responses[i] = s.handle(ctx, codec, req)
  314. }
  315. }
  316. if err := codec.Write(responses); err != nil {
  317. glog.V(logger.Error).Infof("%v\n", err)
  318. codec.Close()
  319. }
  320. }
  321. // readRequest requests the next (batch) request from the codec. It will return the collection of requests, an
  322. // indication if the request was a batch, the invalid request identifier and an error when the request could not be
  323. // read/parsed.
  324. func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, RPCError) {
  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.isPubSub && r.method == unsubscribeMethod {
  335. requests[i] = &serverRequest{id: r.id, isUnsubscribe: true}
  336. argTypes := []reflect.Type{reflect.TypeOf("")}
  337. if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
  338. requests[i].args = args
  339. } else {
  340. requests[i].err = &invalidParamsError{err.Error()}
  341. }
  342. continue
  343. }
  344. if svc, ok = s.services[r.service]; !ok {
  345. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
  346. continue
  347. }
  348. if r.isPubSub { // eth_subscribe
  349. if callb, ok := svc.subscriptions[r.method]; ok {
  350. requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
  351. if r.params != nil && len(callb.argTypes) > 0 {
  352. argTypes := []reflect.Type{reflect.TypeOf("")}
  353. argTypes = append(argTypes, callb.argTypes...)
  354. if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil {
  355. requests[i].args = args[1:] // first one is service.method name which isn't an actual argument
  356. } else {
  357. requests[i].err = &invalidParamsError{err.Error()}
  358. }
  359. }
  360. } else {
  361. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{subscribeMethod, r.method}}
  362. }
  363. continue
  364. }
  365. if callb, ok := svc.callbacks[r.method]; ok {
  366. requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb}
  367. if r.params != nil && len(callb.argTypes) > 0 {
  368. if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil {
  369. requests[i].args = args
  370. } else {
  371. requests[i].err = &invalidParamsError{err.Error()}
  372. }
  373. }
  374. continue
  375. }
  376. requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}}
  377. }
  378. return requests, batch, nil
  379. }