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

Bug 1956081: add sigterm handler to insecurereadyz #1149

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -23,6 +23,7 @@ require (
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.6.1
go.etcd.io/etcd v0.5.0-alpha.5.0.20200910180754-dd1b699fc489
golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073
k8s.io/api v0.21.1
k8s.io/apiextensions-apiserver v0.21.1
k8s.io/apimachinery v0.21.1
Expand Down
42 changes: 41 additions & 1 deletion pkg/cmd/insecurereadyz/readyz.go
@@ -1,14 +1,19 @@
package insecurereadyz

import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"syscall"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/sys/unix"
"k8s.io/apiserver/pkg/server"
"k8s.io/klog/v2"
)

Expand Down Expand Up @@ -99,7 +104,42 @@ func (r *readyzOpts) Run() error {
w.Write(body)
})

shutdownCtx, cancel := context.WithCancel(context.Background())
shutdownHandler := server.SetupSignalHandler()

addr := fmt.Sprintf("0.0.0.0:%d", r.insecurePort)
klog.Infof("Listening on %s", addr)
return http.ListenAndServe(addr, mux)

server := &http.Server{
Addr: addr,
Handler: mux,
BaseContext: func(_ net.Listener) context.Context { return shutdownCtx },
}
go func() {
defer cancel()
<-shutdownHandler
klog.Infof("Received SIGTERM or SIGINT signal, shutting down server.")
server.Shutdown(shutdownCtx)
}()

c := net.ListenConfig{}
c.Control = permitAddressReuse
ln, err := c.Listen(shutdownCtx, "tcp", addr)
if err != nil {
return err
}
err = server.Serve(ln)
if err == http.ErrServerClosed {
err = nil
}
<-shutdownCtx.Done()
return err
}

func permitAddressReuse(network, addr string, conn syscall.RawConn) error {
return conn.Control(func(fd uintptr) {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil {
klog.Warningf("failed to set SO_REUSEADDR on socket: %v", err)
}
})
}
1 change: 1 addition & 0 deletions vendor/modules.txt
Expand Up @@ -401,6 +401,7 @@ golang.org/x/oauth2/internal
# golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9
golang.org/x/sync/singleflight
# golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073
## explicit
golang.org/x/sys/cpu
golang.org/x/sys/internal/unsafeheader
golang.org/x/sys/plan9
Expand Down