server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. "io"
  20. "sync/atomic"
  21. mapset "github.com/deckarep/golang-set"
  22. "github.com/ethereum/go-ethereum/log"
  23. )
  24. const MetadataApi = "rpc"
  25. const EngineApi = "engine"
  26. // CodecOption specifies which type of messages a codec supports.
  27. //
  28. // Deprecated: this option is no longer honored by Server.
  29. type CodecOption int
  30. const (
  31. // OptionMethodInvocation is an indication that the codec supports RPC method calls
  32. OptionMethodInvocation CodecOption = 1 << iota
  33. // OptionSubscriptions is an indication that the codec supports RPC notifications
  34. OptionSubscriptions = 1 << iota // support pub sub
  35. )
  36. // Server is an RPC server.
  37. type Server struct {
  38. services serviceRegistry
  39. idgen func() ID
  40. run int32
  41. codecs mapset.Set
  42. }
  43. // NewServer creates a new server instance with no registered handlers.
  44. func NewServer() *Server {
  45. server := &Server{idgen: randomIDGenerator(), codecs: mapset.NewSet(), run: 1}
  46. // Register the default service providing meta information about the RPC service such
  47. // as the services and methods it offers.
  48. rpcService := &RPCService{server}
  49. server.RegisterName(MetadataApi, rpcService)
  50. return server
  51. }
  52. // RegisterName creates a service for the given receiver type under the given name. When no
  53. // methods on the given receiver match the criteria to be either a RPC method or a
  54. // subscription an error is returned. Otherwise a new service is created and added to the
  55. // service collection this server provides to clients.
  56. func (s *Server) RegisterName(name string, receiver interface{}) error {
  57. return s.services.registerName(name, receiver)
  58. }
  59. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
  60. // the response back using the given codec. It will block until the codec is closed or the
  61. // server is stopped. In either case the codec is closed.
  62. //
  63. // Note that codec options are no longer supported.
  64. func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
  65. defer codec.close()
  66. // Don't serve if server is stopped.
  67. if atomic.LoadInt32(&s.run) == 0 {
  68. return
  69. }
  70. // Add the codec to the set so it can be closed by Stop.
  71. s.codecs.Add(codec)
  72. defer s.codecs.Remove(codec)
  73. c := initClient(codec, s.idgen, &s.services)
  74. <-codec.closed()
  75. c.Close()
  76. }
  77. // serveSingleRequest reads and processes a single RPC request from the given codec. This
  78. // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
  79. // this mode.
  80. func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) {
  81. // Don't serve if server is stopped.
  82. if atomic.LoadInt32(&s.run) == 0 {
  83. return
  84. }
  85. h := newHandler(ctx, codec, s.idgen, &s.services)
  86. h.allowSubscribe = false
  87. defer h.close(io.EOF, nil)
  88. reqs, batch, err := codec.readBatch()
  89. if err != nil {
  90. if err != io.EOF {
  91. codec.writeJSON(ctx, errorMessage(&invalidMessageError{"parse error"}))
  92. }
  93. return
  94. }
  95. if batch {
  96. h.handleBatch(reqs)
  97. } else {
  98. h.handleMsg(reqs[0])
  99. }
  100. }
  101. // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
  102. // requests to finish, then closes all codecs which will cancel pending requests and
  103. // subscriptions.
  104. func (s *Server) Stop() {
  105. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  106. log.Debug("RPC server shutting down")
  107. s.codecs.Each(func(c interface{}) bool {
  108. c.(ServerCodec).close()
  109. return true
  110. })
  111. }
  112. }
  113. // RPCService gives meta information about the server.
  114. // e.g. gives information about the loaded modules.
  115. type RPCService struct {
  116. server *Server
  117. }
  118. // Modules returns the list of RPC services with their version number
  119. func (s *RPCService) Modules() map[string]string {
  120. s.server.services.mu.Lock()
  121. defer s.server.services.mu.Unlock()
  122. modules := make(map[string]string)
  123. for name := range s.server.services.services {
  124. modules[name] = "1.0"
  125. }
  126. return modules
  127. }
  128. // PeerInfo contains information about the remote end of the network connection.
  129. //
  130. // This is available within RPC method handlers through the context. Call
  131. // PeerInfoFromContext to get information about the client connection related to
  132. // the current method call.
  133. type PeerInfo struct {
  134. // Transport is name of the protocol used by the client.
  135. // This can be "http", "ws" or "ipc".
  136. Transport string
  137. // Address of client. This will usually contain the IP address and port.
  138. RemoteAddr string
  139. // Additional information for HTTP and WebSocket connections.
  140. HTTP struct {
  141. // Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket.
  142. Version string
  143. // Header values sent by the client.
  144. UserAgent string
  145. Origin string
  146. Host string
  147. }
  148. }
  149. type peerInfoContextKey struct{}
  150. // PeerInfoFromContext returns information about the client's network connection.
  151. // Use this with the context passed to RPC method handler functions.
  152. //
  153. // The zero value is returned if no connection info is present in ctx.
  154. func PeerInfoFromContext(ctx context.Context) PeerInfo {
  155. info, _ := ctx.Value(peerInfoContextKey{}).(PeerInfo)
  156. return info
  157. }