/
server.go
82 lines (66 loc) · 1.61 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package exporter
import (
"context"
"net"
"sync"
"github.com/insolar/block-explorer/instrumentation/belogger"
"github.com/pkg/errors"
"google.golang.org/grpc"
)
// Server implements introspection gRPC server.
type Server struct {
listen string
grpcServer *grpc.Server
cancel context.CancelFunc
hasStarted bool
startStopMutex *sync.Mutex
}
func NewServer(listen string, grpcServer *grpc.Server) *Server {
return &Server{
listen: listen,
grpcServer: grpcServer,
hasStarted: false,
startStopMutex: &sync.Mutex{},
}
}
func (s *Server) Start(ctx context.Context) error {
if s.grpcServer == nil {
return errors.New("gRPC server is required")
}
s.startStopMutex.Lock()
defer s.startStopMutex.Unlock()
if s.hasStarted {
return nil
}
l, err := net.Listen("tcp", s.listen)
if err != nil {
return errors.Wrapf(err, "failed to start gPRC server on %s", s.listen)
}
ctx, cancel := context.WithCancel(ctx)
s.cancel = cancel
go s.run(ctx, l)
belogger.FromContext(ctx).
Infof("started gPRC server on %s\n", l.Addr())
return nil
}
func (s *Server) Stop(ctx context.Context) error {
s.startStopMutex.Lock()
defer s.startStopMutex.Unlock()
if !s.hasStarted {
return nil
}
if s.cancel != nil {
s.cancel()
}
belogger.FromContext(ctx).
Warn("stop called for not started introspection server")
return nil
}
func (s *Server) run(ctx context.Context, l net.Listener) {
go func(ctx context.Context, grpcServer *grpc.Server) {
err := grpcServer.Serve(l)
if err != nil {
belogger.FromContext(ctx).Error("gRPC server stopped gracefully: ", err)
}
}(ctx, s.grpcServer)
}