Skip to content

Commit

Permalink
Implement Grafana endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
mrusme committed Sep 19, 2024
1 parent 464237d commit 92a9a4b
Show file tree
Hide file tree
Showing 4 changed files with 189 additions and 9 deletions.
65 changes: 61 additions & 4 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/hibiken/asynq"
"github.com/mrusme/overpush/api/grafana"
"github.com/mrusme/overpush/api/messages"
"github.com/mrusme/overpush/fiberzap"
"github.com/mrusme/overpush/lib"
Expand Down Expand Up @@ -82,15 +83,15 @@ func (api *API) attachRoutes() {
bound := c.Bind()

if err := bound.Body(req); err != nil {
return c.JSON(fiber.Map{
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
})
}

if err := validate.Struct(req); err != nil {
return c.JSON(fiber.Map{
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
Expand All @@ -99,7 +100,7 @@ func (api *API) attachRoutes() {

payload, err := json.Marshal(req)
if err != nil {
return c.JSON(fiber.Map{
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
Expand All @@ -109,7 +110,63 @@ func (api *API) attachRoutes() {
api.log.Debug("Enqueueing request", zap.ByteString("payload", payload))
_, err = api.redis.Enqueue(asynq.NewTask("message", payload))
if err != nil {
return c.JSON(fiber.Map{
return c.Status(fiber.ErrInternalServerError.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
})
}

return c.JSON(fiber.Map{
"status": 1,
"request": requestid.FromContext(c),
})
})

api.app.Post("/grafana", func(c fiber.Ctx) error {
req := new(grafana.Request)

bound := c.Bind()

if err := bound.Body(req); err != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
})
}

req.User = c.Query("user")
req.Token = c.Query("token")

if err := validate.Struct(req); err != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
})
}

msg := new(messages.Request)
msg.User = req.User
msg.Token = req.Token
msg.Title = req.Title
msg.Message = req.Message
msg.URL = req.ExternalURL

payload, err := json.Marshal(msg)
if err != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
})
}

api.log.Debug("Enqueueing request", zap.ByteString("payload", payload))
_, err = api.redis.Enqueue(asynq.NewTask("message", payload))
if err != nil {
return c.Status(fiber.ErrInternalServerError.Code).JSON(fiber.Map{
"error": err.Error(),
"status": 0,
"request": requestid.FromContext(c),
Expand Down
117 changes: 117 additions & 0 deletions api/grafana/grafana.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package grafana

import "fmt"

// {
// "receiver": "test",
// "status": "firing",
// "alerts": [
// {
// "status": "firing",
// "labels": {
// "alertname": "TestAlert",
// "instance": "Grafana"
// },
// "annotations": {
// "summary": "Notification test"
// },
// "startsAt": "2024-09-19T02:31:42.985255201Z",
// "endsAt": "0001-01-01T00:00:00Z",
// "generatorURL": "",
// "fingerprint": "57c6d9296de2ad39",
// "silenceURL": "http://stats.0xdead10.cc:3000/alerting/silence/new?alertmanager=grafana&matcher=alertname%3DTestAlert&matcher=instance%3DGrafana",
// "dashboardURL": "",
// "panelURL": "",
// "values": null,
// "valueString": "[ metric='foo' labels={instance=bar} value=10 ]"
// }
// ],
// "groupLabels": {
// "alertname": "TestAlert",
// "instance": "Grafana"
// },
// "commonLabels": {
// "alertname": "TestAlert",
// "instance": "Grafana"
// },
// "commonAnnotations": {
// "summary": "Notification test"
// },
// "externalURL": "http://stats.0xdead10.cc:3000/",
// "version": "1",
// "groupKey": "test-57c6d9296de2ad39-1726713102",
// "truncatedAlerts": 0,
// "orgId": 1,
// "title": "[FIRING:1] TestAlert Grafana ",
// "state": "alerting",
// "message": "**Firing**\n\nValue: [no value]\nLabels:\n - alertname = TestAlert\n - instance = Grafana\nAnnotations:\n - summary = Notification test\nSilence: http://stats.0xdead10.cc:3000/alerting/silence/new?alertmanager=grafana&matcher=alertname%3DTestAlert&matcher=instance%3DGrafana\n"
// }

type Alert struct {
Status string `json:"status",validate:""`
Labels struct {
AlertName string `json:"alertname",validate:""`
Instance string `json:"instance",validate:""`
} `json:"labels",validate:""`
Annotations struct {
Summary string `json:"summary",validate:""`
} `json:"annotations",validate:""`
StartsAt string `json:"startsAt",validate:""`
EndsAt string `json:"endsAt",validate:""`
GeneratorURL string `json:"generatorURL",validate:"http_url"`
Fingerprint string `json:"fingerprint",validate:""`
SilenceURL string `json:"silenceURL",validate:"http_url"`
DashboardURL string `json:"dashboardURL",validate:"http_url"`
PanelURL string `json:"panelURL",validate:"http_url"`
Values string `json:"values",validate:""`
ValueString string `json:"valueString",validate:""`
}

type Request struct {
Token string `json:"token",validate:"required,printascii"`
User string `json:"user",validate:"required,printascii"`

Receiver string `json:"receiver",validate:""`
Status string `json:"status",validate:""`
Alerts []Alert `json:"alerts",validate:""`
GroupLabels struct {
AlertName string `json:"alertname",validate:""`
Instance string `json:"instance",validate:""`
} `json:"groupLabels",validate:""`
CommonLabels struct {
AlertName string `json:"alertname",validate:""`
Instance string `json:"instance",validate:""`
} `json:"commonLabels",validate:""`
CommonAnnotations struct {
Summary string `json:"summary",validate:""`
} `json:"commonAnnotations",validate:""`

ExternalURL string `json:"externalURL",validate:"http_url"`
Version string `json:"version",validate:""`
GroupKey string `json:"groupKey",validate:""`
TruncatedAlerts int `json:"truncatedAlerts",validate:""`
OrgID int `json:"orgId",validate:""`
Title string `json:"title",validate:""`
State string `json:"state",validate:""`
Message string `json:"message",validate:"required"`
}

func (msg *Request) ToString() string {
var s string = ""

s = fmt.Sprintf(
"%s\n\n%s\n",
msg.Title,
msg.Message,
)

if msg.ExternalURL != "" {
s = fmt.Sprintf(
"%s\n%s",
s,
msg.ExternalURL,
)
}

return s
}
10 changes: 8 additions & 2 deletions overpush.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,15 @@ func main() {
}

if config.Debug == "true" {
logger, _ = zap.NewDevelopment()
logcfg := zap.NewDevelopmentConfig()
logcfg.OutputPaths = []string{"stdout"}
logcfg.Level.SetLevel(zap.DebugLevel)
logger, _ = logcfg.Build()
} else {
logger, _ = zap.NewProduction()
logcfg := zap.NewProductionConfig()
logcfg.OutputPaths = []string{"stdout"}
logcfg.Level.SetLevel(zap.InfoLevel)
logger, _ = logcfg.Build()
}
defer logger.Sync()
// TODO: Use sugarLogger
Expand Down
6 changes: 3 additions & 3 deletions worker/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (wrk *Worker) Run() {
Password: wrk.cfg.Redis.Password,
},
asynq.Config{
// Logger: wrk.log,
Logger: wrk.log.Sugar(),
Concurrency: wrk.cfg.Redis.Concurrency,
},
)
Expand All @@ -53,7 +53,7 @@ func (wrk *Worker) Run() {
Password: wrk.cfg.Redis.Password,
},
asynq.Config{
// Logger: wrk.log,
Logger: wrk.log.Sugar(),
Concurrency: wrk.cfg.Redis.Concurrency,
},
)
Expand All @@ -66,7 +66,7 @@ func (wrk *Worker) Run() {
Password: wrk.cfg.Redis.Password,
},
asynq.Config{
// Logger: wrk.log,
Logger: wrk.log.Sugar(),
Concurrency: wrk.cfg.Redis.Concurrency,
},
)
Expand Down

0 comments on commit 92a9a4b

Please sign in to comment.