Skip to content

Commit 09abfff

Browse files
committed
fix: be more idiomatic & address comments
* Use a Context to manage the background server * Use a Context to manage the polling function * Replaced metrics.Server with bg_server.httpBgServer * Made private and moved the polling functionnality into server.go as after using a Context it was nothing more than a single function * Use a signal.NotifyContext to listen to signals instead of manually setting up a waiter and registering it as an extra listener.
1 parent 7306c73 commit 09abfff

4 files changed

Lines changed: 60 additions & 109 deletions

File tree

cmd/csi-rclone-plugin/main.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package main
22

33
import (
4+
"context"
45
"flag"
56
"fmt"
67
"os"
8+
"os/signal"
9+
"syscall"
710
"time"
811

912
"github.com/SwissDataScienceCenter/csi-rclone/pkg/metrics"
@@ -78,10 +81,13 @@ func main() {
7881

7982
root.ParseFlags(os.Args[1:])
8083

81-
if metricsServerConfig.IsEnabled() {
82-
metricsServer := metricsServerConfig.NewServer(&meters, 1*time.Second, 5*time.Second)
84+
if metricsServerConfig.Enable {
85+
// Gracefully exit the metrics background servers
86+
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
87+
defer stop()
88+
89+
metricsServer := metricsServerConfig.NewServer(ctx, 5*time.Second, 30*time.Second, &meters)
8390
go metricsServer.ListenAndServe()
84-
defer metricsServer.Shutdown()
8591
}
8692

8793
if err := root.Execute(); err != nil {

pkg/metrics/bg_server.go

Lines changed: 0 additions & 50 deletions
This file was deleted.

pkg/metrics/server.go

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,99 @@
11
package metrics
22

33
import (
4+
"context"
5+
"errors"
46
"fmt"
57
"net/http"
68
"time"
79

810
"github.com/prometheus/client_golang/prometheus/promhttp"
911
"github.com/spf13/cobra"
12+
"k8s.io/klog"
1013
)
1114

1215
type Server struct {
13-
server httpBgServer
14-
Watcher Watcher
16+
http http.Server
17+
shutdownFinished chan struct{}
1518
}
1619

1720
func (server *Server) ListenAndServe() {
18-
server.server.ListenAndServe()
21+
err := server.http.ListenAndServe()
22+
23+
if errors.Is(err, http.ErrServerClosed) {
24+
// Expected in case of shutdown.
25+
err = nil
26+
} else {
27+
klog.Warning("HTTP server failed: " + err.Error())
28+
}
29+
30+
<-server.shutdownFinished
1931
}
2032

21-
func (server *Server) Shutdown() {
22-
if server.Watcher.tickerStop != nil {
23-
server.Watcher.Stop()
33+
func (server *Server) shutdown(waitForExit context.Context, exitTimeout time.Duration) {
34+
<-waitForExit.Done()
35+
36+
ctx, cancel := context.WithTimeout(context.Background(), exitTimeout)
37+
defer cancel()
38+
39+
err := server.http.Shutdown(ctx)
40+
if err != nil {
41+
klog.Warning("Error while shutting down HTTP server: " + err.Error())
42+
} else {
43+
klog.Info("HTTP server successfully shut down.")
44+
}
45+
close(server.shutdownFinished)
46+
}
47+
48+
type Observable func()
49+
50+
func poll(ctx context.Context, period time.Duration, observe Observable) {
51+
ticker := time.NewTicker(period)
52+
defer ticker.Stop()
53+
54+
for {
55+
select {
56+
case <-ctx.Done():
57+
return
58+
case <-ticker.C:
59+
observe()
60+
}
2461
}
25-
server.server.Shutdown()
2662
}
2763

2864
type ServerConfig struct {
2965
host string
3066
port int16
3167
pathPrefix string
32-
enable bool
68+
Enable bool
3369
}
3470

3571
func (config *ServerConfig) CommandLineParameters(root *cobra.Command) {
3672
root.PersistentFlags().StringVar(&config.host, "metrics-host", "localhost", "Host name or ip address for Prometheus metrics")
3773
root.PersistentFlags().Int16Var(&config.port, "metrics-port", 80, "Port for Prometheus metrics")
38-
root.PersistentFlags().BoolVar(&config.enable, "metrics-enable", false, "Enable Prometheus metrics")
74+
root.PersistentFlags().BoolVar(&config.Enable, "metrics-enable", false, "Enable Prometheus metrics")
3975

4076
config.pathPrefix = "/metrics"
4177
}
4278

43-
func (config *ServerConfig) NewServer(meters *[]Observable, pollDelay, shutdownTimeout time.Duration) *Server {
79+
func (config *ServerConfig) NewServer(ctx context.Context, shutdownTimeout, pollPeriod time.Duration, meters *[]Observable) *Server {
4480
mux := http.NewServeMux()
4581
mux.Handle(config.pathPrefix, promhttp.Handler())
4682

4783
server := Server{
48-
server: httpBgServer{
49-
server: http.Server{Addr: fmt.Sprintf("%s:%d", config.host, config.port), Handler: mux},
50-
shutdownFinished: make(chan struct{}),
51-
shutdownTimeout: shutdownTimeout,
52-
},
84+
http: http.Server{Addr: fmt.Sprintf("%s:%d", config.host, config.port), Handler: mux},
85+
shutdownFinished: make(chan struct{}),
5386
}
5487

55-
server.Watcher.Poll(
88+
go poll(ctx, pollPeriod,
5689
func() {
5790
for _, observer := range *meters {
5891
observer()
5992
}
6093
},
61-
pollDelay,
6294
)
6395

96+
go server.shutdown(ctx, shutdownTimeout)
97+
6498
return &server
6599
}
66-
67-
func (config *ServerConfig) IsEnabled() bool { return config.enable }

pkg/metrics/watcher.go

Lines changed: 0 additions & 37 deletions
This file was deleted.

0 commit comments

Comments
 (0)