-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlifecycle.go
More file actions
276 lines (230 loc) · 8.19 KB
/
lifecycle.go
File metadata and controls
276 lines (230 loc) · 8.19 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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright IBM Corp. 2022, 2026
// SPDX-License-Identifier: MPL-2.0
package consuldp
import (
"context"
"fmt"
"net"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/consul-dataplane/pkg/envoy"
)
const (
// defaultLifecycleBindPort is the port which will serve the proxy lifecycle HTTP
// endpoints on the loopback interface.
defaultLifecycleBindPort = "20300"
cdpLifecycleBindAddr = "127.0.0.1"
cdpLifecycleUrl = "http://" + cdpLifecycleBindAddr
defaultLifecycleShutdownPath = "/graceful_shutdown"
defaultLifecycleStartupPath = "/graceful_startup"
)
// lifecycleConfig handles all configuration related to managing the Envoy proxy
// lifecycle, including exposing management controls via an HTTP server.
type lifecycleConfig struct {
logger hclog.Logger
// consuldp proxy lifecycle management config
shutdownDrainListenersEnabled bool
shutdownGracePeriodSeconds int
gracefulAddr string
gracefulPort int
gracefulShutdownPath string
startupGracePeriodSeconds int
gracefulStartupPath string
dumpEnvoyConfigOnExitEnabled bool
// manager for controlling the Envoy proxy process
proxy envoy.ProxyManager
// consuldp proxy lifecycle management server
lifecycleServer *http.Server
// consuldp proxy lifecycle server control
errorExitCh chan struct{}
running bool
mu sync.Mutex
}
func NewLifecycleConfig(cfg *Config, proxy envoy.ProxyManager) *lifecycleConfig {
return &lifecycleConfig{
shutdownDrainListenersEnabled: cfg.Envoy.ShutdownDrainListenersEnabled,
shutdownGracePeriodSeconds: cfg.Envoy.ShutdownGracePeriodSeconds,
gracefulAddr: cfg.Envoy.GracefulAddr,
gracefulPort: cfg.Envoy.GracefulPort,
gracefulShutdownPath: cfg.Envoy.GracefulShutdownPath,
dumpEnvoyConfigOnExitEnabled: cfg.Envoy.DumpEnvoyConfigOnExitEnabled,
startupGracePeriodSeconds: cfg.Envoy.StartupGracePeriodSeconds,
gracefulStartupPath: cfg.Envoy.GracefulStartupPath,
proxy: proxy,
errorExitCh: make(chan struct{}, 1),
mu: sync.Mutex{},
}
}
func (m *lifecycleConfig) startLifecycleManager(ctx context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.running {
return nil
}
m.logger = hclog.FromContext(ctx).Named("lifecycle")
m.running = true
go func() {
<-ctx.Done()
m.stopLifecycleServer()
}()
// Start the server which will expose HTTP endpoints for proxy lifecycle
// management control
mux := http.NewServeMux()
m.logger.Info(fmt.Sprintf("setting graceful shutdown path: %s\n", m.shutdownPath()))
mux.HandleFunc(m.shutdownPath(), m.gracefulShutdownHandler)
m.logger.Info(fmt.Sprintf("setting graceful startup path: %s\n", m.startupPath()))
mux.HandleFunc(m.startupPath(), m.gracefulStartupHandler)
// Determine what the proxy lifecycle management server bind port is. It can be
// set as a flag.
cdpLifecycleBindAddr := cdpLifecycleBindAddr
cdpLifecycleBindPort := defaultLifecycleBindPort
if m.gracefulAddr != "" {
cdpLifecycleBindAddr = m.gracefulAddr
}
if m.gracefulPort != 0 {
cdpLifecycleBindPort = strconv.Itoa(m.gracefulPort)
}
m.lifecycleServer = &http.Server{
Addr: net.JoinHostPort(cdpLifecycleBindAddr, cdpLifecycleBindPort),
Handler: mux,
}
// Start the proxy lifecycle management server
go m.startLifecycleServer()
return nil
}
// startLifecycleServer starts the main proxy lifecycle management server that
// exposes HTTP endpoints for proxy lifecycle control.
func (m *lifecycleConfig) startLifecycleServer() {
m.logger.Info("starting proxy lifecycle management server", "address", m.lifecycleServer.Addr)
err := m.lifecycleServer.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
m.logger.Error("failed to serve proxy lifecycle management requests", "error", err)
close(m.errorExitCh)
}
}
// stopLifecycleServer stops the consul dataplane proxy lifecycle server
func (m *lifecycleConfig) stopLifecycleServer() {
m.mu.Lock()
defer m.mu.Unlock()
m.running = false
if m.lifecycleServer != nil {
m.logger.Info("stopping the lifecycle management server")
err := m.lifecycleServer.Close()
if err != nil {
m.logger.Warn("error while closing lifecycle server", "error", err)
close(m.errorExitCh)
}
}
}
// lifecycleServerExited is used to signal that the lifecycle server
// recieved a signal to initiate shutdown.
func (m *lifecycleConfig) lifecycleServerExited() <-chan struct{} {
return m.errorExitCh
}
func (m *lifecycleConfig) gracefulShutdownHandler(rw http.ResponseWriter, _ *http.Request) {
// Kick off graceful shutdown in a separate goroutine to avoid blocking
// sending an HTTP response
go m.gracefulShutdown()
// Return HTTP 200 Success
rw.WriteHeader(http.StatusOK)
}
// gracefulShutdown blocks until shutdownGracePeriod seconds have elapsed, and, if
// configured, will drain inbound connections to Envoy listeners during that time.
func (m *lifecycleConfig) gracefulShutdown() {
m.logger.Info("initiating shutdown")
// Create a context that will signal a cancel at the specified duration.
// TODO: should this use lifecycleManager ctx instead of context.Background?
timeout := time.Duration(m.shutdownGracePeriodSeconds) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if m.dumpEnvoyConfigOnExitEnabled {
m.logger.Info("dumping Envoy config to disk")
err := m.proxy.DumpConfig()
if err != nil {
m.logger.Warn("error while attempting to dump Envoy config to disk", "error", err)
}
}
m.logger.Info(fmt.Sprintf("waiting %d seconds before terminating dataplane proxy", m.shutdownGracePeriodSeconds))
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// If shutdownDrainListenersEnabled, initiatie graceful shutdown of Envoy.
// We want to start draining connections from inbound listeners if
// configured, but still allow outbound traffic until gracefulShutdownPeriod
// has elapsed to facilitate a graceful application shutdown.
if m.shutdownDrainListenersEnabled {
err := m.proxy.Drain()
if err != nil {
m.logger.Warn("error while draining Envoy listeners", "error", err)
}
}
// Block until context timeout has elapsed
<-ctx.Done()
// Finish graceful shutdown, quit Envoy proxy
m.logger.Info("shutdown grace period timeout reached")
err := m.proxy.Quit()
if err != nil {
m.logger.Warn("error while shutting down Envoy", "error", err)
}
}()
// Wait for context timeout to elapse
wg.Wait()
}
func (m *lifecycleConfig) gracefulStartupHandler(rw http.ResponseWriter, _ *http.Request) {
//Unlike in gracefulShutdown, we want to delay the OK response until envoy is ready
//in order to block application container.
m.gracefulStartup()
rw.WriteHeader(http.StatusOK)
}
// gracefulStartup blocks until the startup grace period has elapsed or we have confirmed that
// Envoy proxy is ready.
func (m *lifecycleConfig) gracefulStartup() {
if m.startupGracePeriodSeconds == 0 {
m.logger.Info("startupGracePeriodSeconds is set to 0, skipping graceful startup")
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(m.startupGracePeriodSeconds)*time.Second)
defer cancel()
var ready atomic.Bool
go func() {
for ctx.Err() == nil {
r, err := m.proxy.Ready()
if err != nil {
m.logger.Info(fmt.Sprintf("error when querying proxy readiness: %s", err.Error()))
} else {
m.logger.Info(fmt.Sprintf("proxy readiness status: %v", r))
}
if r {
ready.Store(true)
cancel()
break
}
time.Sleep(50 * time.Millisecond)
}
}()
<-ctx.Done()
if !ready.Load() {
m.logger.Warn("grace period elapsed before proxy ready")
} else {
m.logger.Info("proxy is ready within the grace period")
}
}
func (m *lifecycleConfig) shutdownPath() string {
if m.gracefulShutdownPath == "" {
// Set config to allow introspection of default path for testing
m.gracefulShutdownPath = defaultLifecycleShutdownPath
}
return m.gracefulShutdownPath
}
func (m *lifecycleConfig) startupPath() string {
if m.gracefulStartupPath == "" {
// Set config to allow introspection of default path for testing
m.gracefulStartupPath = defaultLifecycleStartupPath
}
return m.gracefulStartupPath
}