Skip to content

Commit

Permalink
Merge pull request #119 from grafana/bugfix/clean-stop
Browse files Browse the repository at this point in the history
fix: clean stop
  • Loading branch information
szkiba authored Dec 18, 2023
2 parents 6a4cbea + 6b9e6fe commit 45fd983
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
11 changes: 10 additions & 1 deletion dashboard/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,16 @@ func (ext *extension) Stop() error {

ext.updateAndSend(nil, newMeter(ext.period, now, ext.options.Tags), stopEvent, now)

return ext.fireStop()
err := ext.fireStop()
if err != nil {
return err
}

if ext.server != nil {
return ext.server.stop()
}

return nil
}

// AddMetricSamples adds the given metric samples to the internal buffer.
Expand Down
38 changes: 32 additions & 6 deletions dashboard/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package dashboard

import (
"errors"
"io/fs"
"net"
"net/http"
Expand Down Expand Up @@ -34,9 +35,14 @@ const (
type webServer struct {
*eventEmitter
*http.ServeMux
server *http.Server
}

func newWebServer(uiFS fs.FS, reportHandler http.Handler, logger logrus.FieldLogger) *webServer { //nolint:ireturn
func newWebServer(
uiFS fs.FS,
reportHandler http.Handler,
logger logrus.FieldLogger,
) *webServer { //nolint:ireturn
srv := &webServer{
eventEmitter: newEventEmitter(eventChannel, logger),
ServeMux: http.NewServeMux(),
Expand All @@ -48,6 +54,11 @@ func newWebServer(uiFS fs.FS, reportHandler http.Handler, logger logrus.FieldLog

srv.HandleFunc("/", rootHandler(pathUI))

srv.server = &http.Server{
Handler: srv.ServeMux,
ReadHeaderTimeout: time.Second,
} //nolint:exhaustruct

return srv
}

Expand All @@ -58,10 +69,9 @@ func (srv *webServer) listenAndServe(addr string) (*net.TCPAddr, error) {
}

go func() {
server := &http.Server{Handler: srv.ServeMux, ReadHeaderTimeout: time.Second} //nolint:exhaustruct

if err := server.Serve(listener); err != nil {
srv.logger.Error(err)
serr := srv.server.Serve(listener)
if serr != nil && !errors.Is(serr, http.ErrServerClosed) {
srv.logger.Error(serr)
}
}()

Expand All @@ -70,10 +80,26 @@ func (srv *webServer) listenAndServe(addr string) (*net.TCPAddr, error) {
return a, nil
}

func (srv *webServer) stop() error {
srv.eventEmitter.Close()

err := srv.server.Close()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}

return nil
}

func rootHandler(uiPath string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { //nolint:varnamelen
if r.URL.Path == "/" {
http.Redirect(w, r, path.Join(uiPath, r.URL.Path)+"?endpoint=/", http.StatusTemporaryRedirect)
http.Redirect(
w,
r,
path.Join(uiPath, r.URL.Path)+"?endpoint=/",
http.StatusTemporaryRedirect,
)

return
}
Expand Down

0 comments on commit 45fd983

Please sign in to comment.