Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add graceful shutdown #867

Merged
merged 7 commits into from
Jan 25, 2024
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 38 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package main

import (
"context"
"errors"
"flag"
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
"time"

"github.com/prometheus/client_golang/prometheus"
Expand Down Expand Up @@ -208,20 +212,41 @@ func main() {

log.Infof("Providing metrics at %s%s", *listenAddress, *metricPath)
log.Debugf("Configured redis addr: %#v", *redisAddr)
if *tlsServerCertFile != "" && *tlsServerKeyFile != "" {
log.Debugf("Bind as TLS using cert %s and key %s", *tlsServerCertFile, *tlsServerKeyFile)
server := &http.Server{
Addr: *listenAddress,
Handler: exp,
}
go func() {
if *tlsServerCertFile != "" && *tlsServerKeyFile != "" {
log.Debugf("Bind as TLS using cert %s and key %s", *tlsServerCertFile, *tlsServerKeyFile)

tlsConfig, err := exp.CreateServerTLSConfig(*tlsServerCertFile, *tlsServerKeyFile, *tlsServerCaCertFile, *tlsServerMinVersion)
if err != nil {
log.Fatal(err)
tlsConfig, err := exp.CreateServerTLSConfig(*tlsServerCertFile, *tlsServerKeyFile, *tlsServerCaCertFile, *tlsServerMinVersion)
if err != nil {
log.Fatal(err)
}
server.TLSConfig = tlsConfig
if err := server.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("TLS Server error: %v", err)
}
} else {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Server error: %v", err)
}
}

server := &http.Server{
Addr: *listenAddress,
TLSConfig: tlsConfig,
Handler: exp}
log.Fatal(server.ListenAndServeTLS("", ""))
} else {
log.Fatal(http.ListenAndServe(*listenAddress, exp))
}()

// graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
_quit := <-quit
log.Infof("Receive exit signal,bye! Signal: %s", _quit.String())
wanghaowei0107 marked this conversation as resolved.
Show resolved Hide resolved
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

// Shutdown the HTTP server gracefully
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown failed: %v", err)
}
log.Infof("Server shut down gracefully")
}
Loading