Skip to content

Commit

Permalink
Allow for shorter graceful shutdown
Browse files Browse the repository at this point in the history
The healthcheck_interval env-var allows a user to specify a
shorter time before shutting down the HTTP server to new
connections.

This change has been tested upstream in the of-watchdog which
wraps this template.

The default behaviour is to continue to use the write_timeout
for a safe shutdown duration.

Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
  • Loading branch information
alexellis committed Nov 2, 2021
1 parent b29fec5 commit b77a0ec
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions template/golang-middleware/main.go
Expand Up @@ -24,6 +24,7 @@ const defaultTimeout = 10 * time.Second
func main() {
readTimeout := parseIntOrDurationValue(os.Getenv("read_timeout"), defaultTimeout)
writeTimeout := parseIntOrDurationValue(os.Getenv("write_timeout"), defaultTimeout)
healthInterval := parseIntOrDurationValue(os.Getenv("healthcheck_interval"), writeTimeout)

s := &http.Server{
Addr: fmt.Sprintf(":%d", 8082),
Expand All @@ -34,7 +35,7 @@ func main() {

http.HandleFunc("/", function.Handle)

listenUntilShutdown(s, writeTimeout)
listenUntilShutdown(s, healthInterval)
}

func listenUntilShutdown(s *http.Server, shutdownTimeout time.Duration) {
Expand All @@ -45,17 +46,14 @@ func listenUntilShutdown(s *http.Server, shutdownTimeout time.Duration) {

<-sig

log.Printf("[entrypoint] SIGTERM received.. shutting down server in %s\n", shutdownTimeout.String())

log.Printf("[entrypoint] SIGTERM: no connections in: %s", shutdownTimeout.String())
<-time.Tick(shutdownTimeout)

if err := s.Shutdown(context.Background()); err != nil {
log.Printf("[entrypoint] Error in Shutdown: %v", err)
}

log.Printf("[entrypoint] No new connections allowed. Exiting in: %s\n", shutdownTimeout.String())

<-time.Tick(shutdownTimeout)
log.Printf("[entrypoint] Exiting")

close(idleConnsClosed)
}()
Expand Down

0 comments on commit b77a0ec

Please sign in to comment.