Skip to content

Commit bb6c702

Browse files
Merge pull request #255 from simonpasquier/OCPBUGS-14033
OCPBUGS-14033: Handle TERM signal gracefully
2 parents 59ac35d + 9d1ff9b commit bb6c702

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

http.go

+8-5
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,20 @@ type Server struct {
2121
Opts *Options
2222
}
2323

24-
func (s *Server) ListenAndServe() {
24+
func (s *Server) ListenAndServe(ctx context.Context) {
2525
if s.Opts.HttpsAddress == "" && s.Opts.HttpAddress == "" {
2626
log.Fatalf("FATAL: must specify https-address or http-address")
2727
}
2828
if s.Opts.HttpsAddress != "" {
29-
go s.ServeHTTPS()
29+
go s.ServeHTTPS(ctx)
3030
}
3131
if s.Opts.HttpAddress != "" {
3232
go s.ServeHTTP()
3333
}
34-
select {}
34+
35+
select {
36+
case <-ctx.Done():
37+
}
3538
}
3639

3740
func (s *Server) ServeHTTP() {
@@ -69,7 +72,7 @@ func (s *Server) ServeHTTP() {
6972
log.Printf("HTTP: closing %s", listener.Addr())
7073
}
7174

72-
func (s *Server) ServeHTTPS() {
75+
func (s *Server) ServeHTTPS(ctx context.Context) {
7376
addr := s.Opts.HttpsAddress
7477

7578
config := oscrypto.SecureTLSConfig(&tls.Config{})
@@ -82,7 +85,7 @@ func (s *Server) ServeHTTPS() {
8285
if err != nil {
8386
log.Fatalf("FATAL: loading tls config (%s, %s) failed - %s", s.Opts.TLSCertFile, s.Opts.TLSKeyFile, err)
8487
}
85-
go servingCertProvider.Run(context.Background(), 1)
88+
go servingCertProvider.Run(ctx, 1)
8689

8790
config.GetCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
8891
// this disregards information from ClientHello but we're not doing SNI anyway

main.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
package main
22

33
import (
4+
"context"
45
"flag"
56
"fmt"
67
"log"
78
"net/http"
89
_ "net/http/pprof"
910
"os"
11+
"os/signal"
1012
"runtime"
1113
"strings"
14+
"syscall"
1215
"time"
1316

1417
"github.com/BurntSushi/toml"
@@ -169,6 +172,16 @@ func main() {
169172
}()
170173
}
171174

175+
ctx, cancel := context.WithCancel(context.Background())
176+
177+
term := make(chan os.Signal, 1)
178+
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
179+
go func() {
180+
<-term
181+
log.Print("received SIGTERM, exiting gracefully...")
182+
cancel()
183+
}()
184+
172185
var h http.Handler = oauthproxy
173186
if opts.RequestLogging {
174187
h = LoggingHandler(os.Stdout, h, true)
@@ -177,5 +190,5 @@ func main() {
177190
Handler: h,
178191
Opts: opts,
179192
}
180-
s.ListenAndServe()
193+
s.ListenAndServe(ctx)
181194
}

0 commit comments

Comments
 (0)