Skip to content

Commit

Permalink
gracefully shutdown server
Browse files Browse the repository at this point in the history
  • Loading branch information
83bytes committed Jun 23, 2024
1 parent c5b6bb0 commit db2ef97
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 9 deletions.
20 changes: 16 additions & 4 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package cmd
import (
"alertmanager/config"
"alertmanager/server"
"fmt"
"os"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -19,19 +21,28 @@ func serverCommandRunE(cmd *cobra.Command, args []string) error {
sPort, _ := cmd.Flags().GetInt("server-port")
mPort, _ := cmd.Flags().GetInt("metric-port")
mgmtPort, _ := cmd.Flags().GetInt("meanagement-port")
// _, _ := cmd.Flags().GetString("config-file")
cFile, _ := cmd.Flags().GetString("config-file")

log := logrus.New()
err := setLogLevelE(log, ll)
if err != nil {
return err
}

b, err := os.ReadFile(cFile)
if err != nil {
return fmt.Errorf("cannot read config file; %s", err)
}
amConfig, err := config.ValidateAndLoad(b)
if err != nil {
return fmt.Errorf("validation failed: please refer to template; %s", err)
}

var s = server.Server{
ServerPort: sPort,
MetricsPort: mPort,
ManagementPort: mgmtPort,
Config: &config.AlertManagerConfig{},
Config: amConfig,
Log: log,
}

Expand All @@ -43,8 +54,9 @@ func init() {
rootCmd.AddCommand(serverCmd)

serverCmd.Flags().Int("server-port", 8081, "Port to listen on")
serverCmd.Flags().Int("metric-port", 8082, "metrics port to listen on")
serverCmd.Flags().Int("management-port", 8083, "management port to listen on")
// todo set up management api and metrics endpoint
// serverCmd.Flags().Int("metric-port", 8082, "metrics port to listen on")
// serverCmd.Flags().Int("management-port", 8083, "management port to listen on")
serverCmd.Flags().String("config-file", "./alert-manager-config.yml", "Path to alert config")
serverCmd.Flags().String("log-level", DEFAULT_LOG_LEVEL, "log-level for alertmanager; options INFO|DEBUG|ERROR")
}
2 changes: 1 addition & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func ValidateAndLoad(b []byte) (AlertManagerConfig, error) {

if len(b) > 0 && amConfig.AlertPipelines == nil {
return AlertManagerConfig{},
fmt.Errorf("unable to load config, please check format; %s", err)
fmt.Errorf("unable to load config, please check format")
}
// todo:
// do better validation
Expand Down
4 changes: 2 additions & 2 deletions scratchpad.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
- --auth-config
- Use [net/http]
- needs 2 min endpoints
- POST / (for getting webhook)
- POST /webhook (for getting webhook)
- POST /~/reload to reload config
- GET /~/config to get current loaded config
- GET /health
- GET /ping
- Use logrus for logging
- Tests

Expand Down
7 changes: 7 additions & 0 deletions server/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package server

import "github.com/gofiber/fiber/v2"

func alertWebhookHandler(c *fiber.Ctx) error {
return c.SendString("pong")
}
34 changes: 32 additions & 2 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package server
import (
"alertmanager/config"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"time"

"github.com/sirupsen/logrus"

Expand All @@ -15,7 +19,7 @@ type Server struct {
ServerPort int
MetricsPort int
ManagementPort int
Config *config.AlertManagerConfig
Config config.AlertManagerConfig
Log *logrus.Logger
}

Expand All @@ -24,12 +28,38 @@ func (s *Server) Start() error {

app := fiber.New()

// handle gradeful app shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt) // SIGINT

var serverShutDownWG sync.WaitGroup // wait for the server to shutdown cleanly

// shutdown server upon SIGINT and signal the waitgroup
go func() {
<-c

s.Log.Info("shutting down server cleanly; please wait :)")
serverShutDownWG.Add(1)
defer serverShutDownWG.Done()

_ = app.ShutdownWithTimeout(time.Second * 30)
}()

// request logger middlewear
// should be okay as long the server is low-volume
// maybe we can configure to log only bad / failed reqs
app.Use(logger.New())

app.Get("/ping", func(c *fiber.Ctx) error {
return c.SendString("pong")
})

app.Listen(":" + strconv.Itoa(s.ServerPort))
app.Post("/webhook/", alertWebhookHandler)

if err := app.Listen(":" + strconv.Itoa(s.ServerPort)); err != nil {
s.Log.Error("server: unable to start server", err)
}

serverShutDownWG.Wait()
return nil
}

0 comments on commit db2ef97

Please sign in to comment.