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

fix: support configuration of HTTP server address #1365

Merged
merged 5 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
82 changes: 45 additions & 37 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ type Command struct {
telemetryPrefix string
prometheus bool
prometheusNamespace string
prometheusAddress string

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We also need httpAddress, right? Otherwise, the probe will fail (am I missing something?).

prometheusPort string

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] Since it’s prometheusPort, what about healthCheckPort instead of httpPort?

healthCheck bool
httpPort string
}
Expand Down Expand Up @@ -228,11 +230,15 @@ func NewCommand(opts ...Option) *Command {
cmd.PersistentFlags().StringVar(&c.telemetryPrefix, "telemetry-prefix", "",
"Prefix for Cloud Monitoring metrics.")
cmd.PersistentFlags().BoolVar(&c.prometheus, "prometheus", false,
"Enable Prometheus HTTP endpoint /metrics on localhost")
"Enable Prometheus HTTP endpoint /metrics")
cmd.PersistentFlags().StringVar(&c.prometheusNamespace, "prometheus-namespace", "",
"Use the provided Prometheus namespace for metrics")
cmd.PersistentFlags().StringVar(&c.httpPort, "http-port", "9090",
"Port for Prometheus and health check server")
cmd.PersistentFlags().StringVar(&c.prometheusAddress, "prometheus-address", "localhost",
"Address for Prometheus server")
cmd.PersistentFlags().StringVar(&c.prometheusPort, "prometheus-port", "9090",
"Port for the Prometheus server")
cmd.PersistentFlags().StringVar(&c.httpPort, "http-port", "8090",
"Port for the health check server")
cmd.PersistentFlags().BoolVar(&c.healthCheck, "health-check", false,
"Enables health check endpoints /startup, /liveness, and /readiness on localhost.")
cmd.PersistentFlags().StringVar(&c.conf.APIEndpointURL, "sqladmin-api-endpoint", "",
Expand Down Expand Up @@ -454,22 +460,26 @@ func runSignalWrapper(cmd *Command) error {
}()
}

var (
needsHTTPServer bool
mux = http.NewServeMux()
)
// shutdownCh wil produce any available error from any goroutine started
// below.
shutdownCh := make(chan error)

if cmd.prometheus {
needsHTTPServer = true
e, err := prometheus.NewExporter(prometheus.Options{
Namespace: cmd.prometheusNamespace,
})
if err != nil {
return err
}
mux := http.NewServeMux()
mux.Handle("/metrics", e)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%s", cmd.prometheusAddress, cmd.prometheusPort),
Handler: mux,
}
startHTTPServer(ctx, cmd.logger, srv, shutdownCh)
}

shutdownCh := make(chan error)
// watch for sigterm / sigint signals
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
Expand Down Expand Up @@ -517,42 +527,17 @@ func runSignalWrapper(cmd *Command) error {

notify := func() {}
if cmd.healthCheck {
needsHTTPServer = true
hc := healthcheck.NewCheck(p, cmd.logger)
mux := http.NewServeMux()
mux.HandleFunc("/startup", hc.HandleStartup)
mux.HandleFunc("/readiness", hc.HandleReadiness)
mux.HandleFunc("/liveness", hc.HandleLiveness)
notify = hc.NotifyStarted
}

// Start the HTTP server if anything requiring HTTP is specified.
if needsHTTPServer {
server := &http.Server{
srv := &http.Server{
Addr: fmt.Sprintf("localhost:%s", cmd.httpPort),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we be putting 0.0.0.0 here?

Handler: mux,
}
// Start the HTTP server.
go func() {
err := server.ListenAndServe()
if err == http.ErrServerClosed {
return
}
if err != nil {
shutdownCh <- fmt.Errorf("failed to start HTTP server: %v", err)
}
}()
// Handle shutdown of the HTTP server gracefully.
go func() {
select {
case <-ctx.Done():
// Give the HTTP server a second to shutdown cleanly.
ctx2, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := server.Shutdown(ctx2); err != nil {
cmd.logger.Errorf("failed to shutdown Prometheus HTTP server: %v\n", err)
}
}
}()
startHTTPServer(ctx, cmd.logger, srv, shutdownCh)
}

go func() { shutdownCh <- p.Serve(ctx, notify) }()
Expand All @@ -568,3 +553,26 @@ func runSignalWrapper(cmd *Command) error {
}
return err
}

func startHTTPServer(ctx context.Context, logger cloudsql.Logger, srv *http.Server, shutdownCh chan<- error) {
// Start the HTTP server.
go func() {
err := srv.ListenAndServe()
if err == http.ErrServerClosed {
return
}
if err != nil {
shutdownCh <- fmt.Errorf("failed to start HTTP server: %v", err)
}
}()
// Handle shutdown of the HTTP server gracefully.
go func() {
<-ctx.Done()
// Give the HTTP server a second to shutdown cleanly.
ctx2, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Shutdown(ctx2); err != nil {
logger.Errorf("failed to shutdown Prometheus HTTP server: %v\n", err)
}
}()
}
7 changes: 6 additions & 1 deletion cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,12 @@ func TestPrometheusMetricsEndpoint(t *testing.T) {
// Keep the test output quiet
c.SilenceUsage = true
c.SilenceErrors = true
c.SetArgs([]string{"--prometheus", "my-project:my-region:my-instance"})
c.SetArgs([]string{
"--prometheus",
"--prometheus-address", "localhost",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need a test where this isn't localhost. That's the default value

"--prometheus-port", "9090",
"my-project:my-region:my-instance",
})

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
Expand Down
6 changes: 3 additions & 3 deletions tests/connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,19 +101,19 @@ func testHealthCheck(t *testing.T, connName string) {

tryDial := func(t *testing.T) *http.Response {
var (
err error
dErr error
resp *http.Response
)
for i := 0; i < 10; i++ {
resp, err = http.Get("http://localhost:9090/readiness")
resp, dErr = http.Get("http://localhost:8090/readiness")
if err != nil {
time.Sleep(100 * time.Millisecond)
}
if resp != nil {
return resp
}
}
t.Fatalf("HTTP GET failed: %v", err)
t.Fatalf("HTTP GET failed: %v", dErr)
return nil
}

Expand Down