server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. // CodecOption specifies which type of messages a codec supports.
  26. //
  27. // Deprecated: this option is no longer honored by Server.
  28. type CodecOption int
  29. const (
  30. // OptionMethodInvocation is an indication that the codec supports RPC method calls
  31. OptionMethodInvocation CodecOption = 1 << iota
  32. // OptionSubscriptions is an indication that the codec supports RPC notifications
  33. OptionSubscriptions = 1 << iota // support pub sub
  34. )
  35. // Server is an RPC server.
  36. type Server struct {
  37. services serviceRegistry
  38. idgen func() ID
  39. run int32
  40. codecs mapset.Set
  41. }
  42. // NewServer creates a new server instance with no registered handlers.
  43. func NewServer() *Server {
  44. server := &Server{idgen: randomIDGenerator(), codecs: mapset.NewSet(), run: 1}
  45. // Register the default service providing meta information about the RPC service such
  46. // as the services and methods it offers.
  47. rpcService := &RPCService{server}
  48. server.RegisterName(MetadataApi, rpcService)
  49. return server
  50. }
  51. // RegisterName creates a service for the given receiver type under the given name. When no
  52. // methods on the given receiver match the criteria to be either a RPC method or a
  53. // subscription an error is returned. Otherwise a new service is created and added to the
  54. // service collection this server provides to clients.
  55. func (s *Server) RegisterName(name string, receiver interface{}) error {
  56. return s.services.registerName(name, receiver)
  57. }
  58. // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
  59. // the response back using the given codec. It will block until the codec is closed or the
  60. // server is stopped. In either case the codec is closed.
  61. //
  62. // Note that codec options are no longer supported.
  63. func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
  64. defer codec.close()
  65. // Don't serve if server is stopped.
  66. if atomic.LoadInt32(&s.run) == 0 {
  67. return
  68. }
  69. // Add the codec to the set so it can be closed by Stop.
  70. s.codecs.Add(codec)
  71. defer s.codecs.Remove(codec)
  72. c := initClient(codec, s.idgen, &s.services)
  73. <-codec.closed()
  74. c.Close()
  75. }
  76. // serveSingleRequest reads and processes a single RPC request from the given codec. This
  77. // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
  78. // this mode.
  79. func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) {
  80. // Don't serve if server is stopped.
  81. if atomic.LoadInt32(&s.run) == 0 {
  82. return
  83. }
  84. h := newHandler(ctx, codec, s.idgen, &s.services)
  85. h.allowSubscribe = false
  86. defer h.close(io.EOF, nil)
  87. reqs, batch, err := codec.readBatch()
  88. if err != nil {
  89. if err != io.EOF {
  90. codec.writeJSON(ctx, errorMessage(&invalidMessageError{"parse error"}))
  91. }
  92. return
  93. }
  94. if batch {
  95. h.handleBatch(ctx, reqs)
  96. } else {
  97. h.handleMsg(ctx, reqs[0])
  98. }
  99. }
  100. // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
  101. // requests to finish, then closes all codecs which will cancel pending requests and
  102. // subscriptions.
  103. func (s *Server) Stop() {
  104. if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
  105. log.Debug("RPC server shutting down")
  106. s.codecs.Each(func(c interface{}) bool {
  107. c.(ServerCodec).close()
  108. return true
  109. })
  110. }
  111. }
  112. // RPCService gives meta information about the server.
  113. // e.g. gives information about the loaded modules.
  114. type RPCService struct {
  115. server *Server
  116. }
  117. // Modules returns the list of RPC services with their version number
  118. func (s *RPCService) Modules() map[string]string {
  119. s.server.services.mu.Lock()
  120. defer s.server.services.mu.Unlock()
  121. modules := make(map[string]string)
  122. for name := range s.server.services.services {
  123. modules[name] = "1.0"
  124. }
  125. return modules
  126. }