-
Notifications
You must be signed in to change notification settings - Fork 2
/
example.go
199 lines (161 loc) · 5.85 KB
/
example.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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"syscall"
"time"
"github.com/skovtunenko/graterm"
)
// Instructions:
// - run the application, reach out to http://localhost:8080/
// - terminate the application (CTRL+C)
// - investigate the log output
const hostPort = ":8080"
const (
globalTerminationTimeout = 40 * time.Second
httpServerTerminationTimeout = 5 * time.Second
httpServerControllerSleepTime = 15 * time.Second
messagingTerminationTimeout = 1 * time.Second
fastDBTerminationTimeout = 1 * time.Second
slowDBTerminationTimeout = 3 * time.Second
slowDBSleepTime = 5 * time.Second // Termination of SlowDB can't be finished in time
)
const (
HTTPServerTerminationOrder graterm.Order = 0
MessagingTerminationOrder graterm.Order = 1
FastDBTerminationOrder graterm.Order = 2
SlowDBTerminationOrder graterm.Order = 2
)
func main() {
logger := log.Default()
logger.Println("Application started...")
// ...Some root context for the whole application... (or it can be just context.Background())
rootCtx, rootCancel := context.WithCancel(context.Background())
defer rootCancel()
terminator, appCtx := graterm.NewWithSignals(rootCtx, syscall.SIGINT, syscall.SIGTERM)
terminator.SetLogger(logger) // Optional step
// Wire application components:
slowDB := NewSlowDB(terminator, logger)
fastDB := NewFastDB(terminator, logger)
messaging := NewMessaging(terminator, logger)
srv := NewServer(terminator, logger)
app := NewApplication(logger, srv, messaging, slowDB, fastDB)
app.Run()
if err := terminator.Wait(appCtx, globalTerminationTimeout); err != nil {
logger.Printf("graceful termination period is timed out: %+v", err)
}
logger.Println("Application ended.")
}
type Application struct {
Log *log.Logger
Server *Server
Messaging *Messaging
SlowDB *SlowDB
FastDB *FastDB
}
func NewApplication(log *log.Logger, server *Server, messaging *Messaging, slowDB *SlowDB, fastDB *FastDB) *Application {
return &Application{Log: log, Server: server, Messaging: messaging, SlowDB: slowDB, FastDB: fastDB}
}
func (a *Application) Run() {
a.SlowDB.Init()
a.FastDB.Init()
a.Messaging.Init()
a.Server.Init()
}
type Server struct {
logger *log.Logger
terminator *graterm.Terminator
}
func NewServer(terminator *graterm.Terminator, logger *log.Logger) *Server {
return &Server{terminator: terminator, logger: logger}
}
func (s *Server) Init() {
defer s.logger.Println("HTTP Server initialized")
httpServer := &http.Server{
Addr: hostPort,
Handler: http.DefaultServeMux,
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
select {
case <-time.After(httpServerControllerSleepTime): // Simulate long-running in-flight HTTP request processing
s.logger.Println("HTTP Server controller finished")
case <-ctx.Done():
s.logger.Printf("HTTP Server controller interrupted because of: %+v\n", ctx.Err())
}
fmt.Fprintf(w, "hello, world!\nSlept for %v seconds\n", httpServerControllerSleepTime)
})
go func() {
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("terminated HTTP Server: %+v", err)
}
}()
s.terminator.WithOrder(HTTPServerTerminationOrder).
WithName("HTTPServer"). // setting a Name is optional and will be useful only if logger instance provided
Register(httpServerTerminationTimeout, func(ctx context.Context) {
s.logger.Println("terminating HTTP Server component...")
defer s.logger.Println("...HTTP Server component terminated")
if err := httpServer.Shutdown(ctx); err != nil { // stop terminating HTTP Server if the time for that is over.
s.logger.Printf("shutdown HTTP Server: %+v", err)
}
})
s.logger.Printf("HTTP Server started on: %q\n", hostPort)
}
type Messaging struct {
logger *log.Logger
terminator *graterm.Terminator
}
func NewMessaging(terminator *graterm.Terminator, logger *log.Logger) *Messaging {
return &Messaging{terminator: terminator, logger: logger}
}
func (m *Messaging) Init() {
defer m.logger.Println("Messaging initialized")
m.terminator.WithOrder(MessagingTerminationOrder).
WithName("Messaging"). // setting a Name is optional and will be useful only if logger instance provided
Register(messagingTerminationTimeout, func(ctx context.Context) {
m.logger.Println("terminating Messaging component...")
defer m.logger.Println("...Messaging component terminated")
})
}
type FastDB struct {
logger *log.Logger
terminator *graterm.Terminator
}
func NewFastDB(terminator *graterm.Terminator, logger *log.Logger) *FastDB {
return &FastDB{terminator: terminator, logger: logger}
}
func (d *FastDB) Init() {
defer d.logger.Println("FastDB initialized")
d.terminator.WithOrder(FastDBTerminationOrder).
WithName("FastDB"). // setting a Name is optional and will be useful only if logger instance provided
Register(fastDBTerminationTimeout, func(ctx context.Context) {
d.logger.Println("terminating FastDB component...")
defer d.logger.Println("...FastDB component terminated")
panic(errors.New("BOOM!"))
})
}
type SlowDB struct {
logger *log.Logger
terminator *graterm.Terminator
}
func NewSlowDB(terminator *graterm.Terminator, logger *log.Logger) *SlowDB {
return &SlowDB{terminator: terminator, logger: logger}
}
func (d *SlowDB) Init() {
defer d.logger.Println("SlowDB initialized")
d.terminator.WithOrder(SlowDBTerminationOrder).
WithName("SlowDB"). // setting a Name is optional and will be useful only if logger instance provided
Register(slowDBTerminationTimeout, func(ctx context.Context) {
d.logger.Println("terminating SlowDB component...")
defer d.logger.Println("...SlowDB component terminated")
select {
case <-time.After(slowDBSleepTime):
d.logger.Println("SlowDB cleanup finished")
case <-ctx.Done():
d.logger.Printf("SlowDB termination interrupted because of: %+v\n", ctx.Err())
}
})
}