-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc_server.go
73 lines (58 loc) · 1.4 KB
/
grpc_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
package serverutils
import (
"context"
"fmt"
"net"
"google.golang.org/grpc"
)
// GrpcServer represents an instance
// of *grpc.Server, which gracefully shutdowns
// and has a status
type GrpcServer struct {
status Status
server *grpc.Server
}
// NewGrpcServer creates a new instance
// of *GrpcServer
func NewGrpcServer(server *grpc.Server) *GrpcServer {
return &GrpcServer{server: server}
}
// Make sure struct implements interface.
var _ Server = &GrpcServer{}
var _ serverOperations = &GrpcServer{}
func (g *GrpcServer) Run(ctx context.Context, req RunRequest) error {
return startServer(ctx, g, req)
}
func (g *GrpcServer) Status() Status {
return g.status
}
func (g *GrpcServer) serve(port int32) error {
// Start a new connection on given port
conn, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return fmt.Errorf("failed to listen on port %d: %s", port, err)
}
// Update server status to Started
g.status = Running
// Serve gRPC server
err = g.server.Serve(conn)
if err != nil {
return fmt.Errorf("failed to serve gRPC connection: %s", err)
}
// No error occured, exit
return nil
}
func (g *GrpcServer) gracefullyShutdown(ctx context.Context) error {
doneCh := make(chan bool, 1)
go func() {
g.server.GracefulStop()
doneCh <- true
// Update server status to Closed
g.status = Stopped
}()
select {
case <-ctx.Done():
case <-doneCh:
}
return nil
}