You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.4 KiB

8 years ago
8 years ago
  1. package server
  2. import (
  3. "context"
  4. "net"
  5. "google.golang.org/grpc"
  6. "github.com/tendermint/tendermint/abci/types"
  7. "github.com/tendermint/tendermint/libs/log"
  8. tmnet "github.com/tendermint/tendermint/libs/net"
  9. "github.com/tendermint/tendermint/libs/service"
  10. )
  11. type GRPCServer struct {
  12. service.BaseService
  13. logger log.Logger
  14. proto string
  15. addr string
  16. listener net.Listener
  17. server *grpc.Server
  18. app types.ABCIApplicationServer
  19. }
  20. // NewGRPCServer returns a new gRPC ABCI server
  21. func NewGRPCServer(logger log.Logger, protoAddr string, app types.ABCIApplicationServer) service.Service {
  22. proto, addr := tmnet.ProtocolAndAddress(protoAddr)
  23. s := &GRPCServer{
  24. logger: logger,
  25. proto: proto,
  26. addr: addr,
  27. listener: nil,
  28. app: app,
  29. }
  30. s.BaseService = *service.NewBaseService(logger, "ABCIServer", s)
  31. return s
  32. }
  33. // OnStart starts the gRPC service.
  34. func (s *GRPCServer) OnStart(ctx context.Context) error {
  35. ln, err := net.Listen(s.proto, s.addr)
  36. if err != nil {
  37. return err
  38. }
  39. s.listener = ln
  40. s.server = grpc.NewServer()
  41. types.RegisterABCIApplicationServer(s.server, s.app)
  42. s.logger.Info("Listening", "proto", s.proto, "addr", s.addr)
  43. go func() {
  44. go func() {
  45. <-ctx.Done()
  46. s.server.GracefulStop()
  47. }()
  48. if err := s.server.Serve(s.listener); err != nil {
  49. s.logger.Error("Error serving gRPC server", "err", err)
  50. }
  51. }()
  52. return nil
  53. }
  54. // OnStop stops the gRPC server.
  55. func (s *GRPCServer) OnStop() {
  56. s.server.Stop()
  57. }