-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
114 lines (94 loc) · 2.39 KB
/
server.go
File metadata and controls
114 lines (94 loc) · 2.39 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package serverutils
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/clubcedille/logger"
)
type Status int
const (
// Running is the status
// for a running server
Running Status = iota
// Stopped is the status
// for a stopped server
Stopped
)
// RunRequest is a set of parameters
// passed to the 'Run' function of each
// server
type RunRequest struct {
// Port is the port number on which
// the server will listen to
Port int32
// ShutdownTimeoutMs is the amount
// of milliseconds to wait for when
// shutting down the server
ShutdownTimeoutMs int32
}
// Server represents any kind of server
// that is able to run, shutdown and
// fetch a status from.
type Server interface {
// Run runs the server on a given port
// and gracefully shutdowns if necessary
Run(ctx context.Context, req RunRequest) error
// Status returns the current status
// of the server
Status() Status
}
// serverOperations is an internal interface meant
// to serve as a helper for server functions.
type serverOperations interface {
gracefullyShutdown(ctx context.Context) error
serve(port int32) error
}
func startServer(ctx context.Context, s serverOperations, req RunRequest) error {
ctx, cancel := context.WithTimeout(
ctx,
time.Millisecond*time.Duration(req.ShutdownTimeoutMs),
)
defer cancel()
logs := logger.NewFromContextOrDefault(ctx)
// Catch some signals and handle them gracefully
sigCh := make(chan os.Signal, 1)
errCh := make(chan error, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
sig := <-sigCh
logs.Errorf("got signal %v, attempting graceful shutdown\n", sig)
cancel()
// Pass returned error from shutdown
// to error channel
if err := s.gracefullyShutdown(ctx); err != nil {
errCh <- err
}
// grpc.Stop() // leads to error while receiving stream response: rpc error: code = Unavailable desc = transport is closing
wg.Done()
}()
// Catch error and return it
select {
case <-ctx.Done():
case err := <-errCh:
return fmt.Errorf("failed to shutdown server: %s", err)
}
// Close channel after function ends
go func() {
defer close(errCh)
}()
// Log what's happening
logs.Infof("Server running on port %d\n", req.Port)
// Start the gRPC server
err := s.serve(req.Port)
if err != nil {
return fmt.Errorf("failed to serve connection: %s", err)
}
wg.Wait()
return nil
}