Skip to content

Commit

Permalink
set the results data for webhook
Browse files Browse the repository at this point in the history
[skip ci]
  • Loading branch information
adityathebe committed Oct 30, 2023
1 parent 9ab771f commit 1075983
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 18 deletions.
2 changes: 1 addition & 1 deletion fixtures/external/alertmanager.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ metadata:
spec:
schedule: "@every 1m" # Disregarded
webhook:
- name: my-webhook
name: my-webhook
1 change: 1 addition & 0 deletions pkg/api/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type HTTPSuccess struct {
Payload any `json:"payload,omitempty"`
}

// WriteError writes the error to the HTTP response with appropriate status code
func WriteError(c echo.Context, err error) error {
code, message := ErrorCode(err), ErrorMessage(err)

Expand Down
55 changes: 39 additions & 16 deletions pkg/api/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package api

import (
goctx "context"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/flanksource/canary-checker/api/context"
Expand All @@ -15,27 +17,50 @@ import (
"github.com/labstack/echo/v4"
)

const webhookBodyLimit = 10 * 1024 // 10 MB

type CheckData struct {
Headers map[string]string `json:"headers"`
JSON map[string]any `json:"json,omitempty"`
Content string `json:"content,omitempty"`
}

func WebhookHandler(c echo.Context) error {
id := c.Param("id")

body := make(map[string]any)
if err := c.Bind(&body); err != nil {
return WriteError(c, Errorf(EINVALID, "invalid request body: %v", err))
}

authToken := c.QueryParam("token")
if authToken == "" {
authToken = c.Request().Header.Get("Webhook-Token")
}

if err := webhookHandler(c.Request().Context(), id, authToken, body); err != nil {
data := CheckData{
Headers: make(map[string]string),
}
for k := range c.Request().Header {
data.Headers[k] = c.Request().Header.Get(k)
}

if c.Request().Header.Get("Content-Type") == "application/json" {
if err := json.NewDecoder(c.Request().Body).Decode(&data.JSON); err != nil {
return WriteError(c, err)
}
} else {
b, err := io.ReadAll(io.LimitReader(c.Request().Body, webhookBodyLimit))
if err != nil {
return WriteError(c, err)
}

data.Content = string(b)
}

if err := webhookHandler(c.Request().Context(), id, authToken, data); err != nil {
return WriteError(c, err)
}

return c.JSON(http.StatusOK, &HTTPSuccess{Message: "ok"})
}

func webhookHandler(ctx goctx.Context, id, authToken string, body map[string]any) error {
func webhookHandler(ctx goctx.Context, id, authToken string, data CheckData) error {
webhookChecks, err := db.FindChecks(context.DefaultContext.Wrap(ctx), id, checks.WebhookCheckType)
if err != nil {
return err
Expand Down Expand Up @@ -66,7 +91,7 @@ func webhookHandler(ctx goctx.Context, id, authToken string, body map[string]any

// Authorization
if webhook.Token != nil {
token, err := duty.GetEnvValueFromCache(nil, *webhook.Token, canary.Namespace) // TODO: K8s dependency
token, err := duty.GetEnvValueFromCache(context.DefaultContext.Kubernetes(), *webhook.Token, canary.Namespace)
if err != nil {
return err
}
Expand All @@ -76,20 +101,18 @@ func webhookHandler(ctx goctx.Context, id, authToken string, body map[string]any
}
}

// TODO: For alert manager, the alerts are in body["alerts"].
// We probably need to make the field configurable.

// We create the check from the request's body ??
var results pkg.Results
result := pkg.Success(webhook, *canary)
results = append(results, result)
result.AddDetails(body["alerts"])
result.AddDetails(data)

scrapeCtx := context.New(nil, nil, db.Gorm, db.Pool, *canary)
results := []*pkg.CheckResult{result}

scrapeCtx := context.New(context.DefaultContext.Kommons(), context.DefaultContext.Kubernetes(), db.Gorm, db.Pool, *canary)
transformedResults := checks.TransformResults(scrapeCtx, results)
results = append(results, transformedResults...)

checks.ExportCheckMetrics(scrapeCtx, transformedResults)
_ = checks.ProcessResults(scrapeCtx, results)

// TODO: persist these results
return nil
}
2 changes: 1 addition & 1 deletion pkg/db/canary.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ func FindCheck(canary pkg.Canary, name string) (*pkg.Check, error) {
}

func FindChecks(ctx context.Context, idOrName, checkType string) ([]models.Check, error) {
query := Gorm.
query := ctx.DB().
Where("agent_id = ?", uuid.Nil.String()).
Where("type = ?", checkType).
Where("deleted_at IS NULL")
Expand Down

0 comments on commit 1075983

Please sign in to comment.