Skip to content

Commit

Permalink
OCPBUGS-14033: Handle TERM signal gracefully
Browse files Browse the repository at this point in the history
When a pod is evicted, the container runtime will send a TERM signal to
the PID 1 of all containers. If a container doesn't catch the signal,
the process will exit with a non-zero code and Kubernetes might consider
the pod status to be Failed.

See
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination

Signed-off-by: Simon Pasquier <spasquie@redhat.com>
  • Loading branch information
simonpasquier committed Jun 1, 2023
1 parent 59ac35d commit 9d1ff9b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
13 changes: 8 additions & 5 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ type Server struct {
Opts *Options
}

func (s *Server) ListenAndServe() {
func (s *Server) ListenAndServe(ctx context.Context) {
if s.Opts.HttpsAddress == "" && s.Opts.HttpAddress == "" {
log.Fatalf("FATAL: must specify https-address or http-address")
}
if s.Opts.HttpsAddress != "" {
go s.ServeHTTPS()
go s.ServeHTTPS(ctx)
}
if s.Opts.HttpAddress != "" {
go s.ServeHTTP()
}
select {}

select {
case <-ctx.Done():
}
}

func (s *Server) ServeHTTP() {
Expand Down Expand Up @@ -69,7 +72,7 @@ func (s *Server) ServeHTTP() {
log.Printf("HTTP: closing %s", listener.Addr())
}

func (s *Server) ServeHTTPS() {
func (s *Server) ServeHTTPS(ctx context.Context) {
addr := s.Opts.HttpsAddress

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

config.GetCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
// this disregards information from ClientHello but we're not doing SNI anyway
Expand Down
15 changes: 14 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package main

import (
"context"
"flag"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"

"github.com/BurntSushi/toml"
Expand Down Expand Up @@ -169,6 +172,16 @@ func main() {
}()
}

ctx, cancel := context.WithCancel(context.Background())

term := make(chan os.Signal, 1)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
go func() {
<-term
log.Print("received SIGTERM, exiting gracefully...")
cancel()
}()

var h http.Handler = oauthproxy
if opts.RequestLogging {
h = LoggingHandler(os.Stdout, h, true)
Expand All @@ -177,5 +190,5 @@ func main() {
Handler: h,
Opts: opts,
}
s.ListenAndServe()
s.ListenAndServe(ctx)
}

0 comments on commit 9d1ff9b

Please sign in to comment.