File size: 4,020 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
package genericapi
import (
"database/sql"
"encoding/json"
"io"
"mime"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
"github.com/target/goalert/alert"
"github.com/target/goalert/auth"
"github.com/target/goalert/permission"
"github.com/target/goalert/retry"
"github.com/target/goalert/util/errutil"
"github.com/target/goalert/validation/validate"
)
// Handler responds to generic API requests
type Handler struct {
c Config
}
// NewHandler creates a new Handler, registering generic API routes using chi.
func NewHandler(c Config) *Handler {
return &Handler{c: c}
}
// ServeUserAvatar will serve a redirect for a users avatar image.
func (h *Handler) ServeUserAvatar(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
u, err := h.c.UserStore.FindOne(ctx, req.PathValue("userID"))
if errors.Is(err, sql.ErrNoRows) {
http.NotFound(w, req)
return
}
if errutil.HTTPError(ctx, w, err) {
return
}
fullSize := req.FormValue("size") == "large"
http.Redirect(w, req, u.ResolveAvatarURL(fullSize), http.StatusFound)
}
// ServeHeartbeatCheck serves the heartbeat check-in endpoint.
func (h *Handler) ServeHeartbeatCheck(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := retry.DoTemporaryError(func(_ int) error {
return h.c.HeartbeatStore.RecordHeartbeat(ctx, r.PathValue("heartbeatID"))
},
retry.Log(ctx),
retry.Limit(12),
retry.FibBackoff(time.Second),
)
if errors.Is(err, sql.ErrNoRows) {
auth.Delay(ctx)
http.NotFound(w, r)
return
}
if errutil.HTTPError(ctx, w, err) {
return
}
}
// ServeCreateAlert allows creating or closing an alert.
func (h *Handler) ServeCreateAlert(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := permission.LimitCheckAny(ctx, permission.Service)
if errutil.HTTPError(ctx, w, err) {
return
}
serviceID := permission.ServiceID(ctx)
summary := r.FormValue("summary")
details := r.FormValue("details")
action := r.FormValue("action")
dedup := r.FormValue("dedup")
meta := make(map[string]string)
for _, v := range r.Form["meta"] {
key, val, ok := strings.Cut(v, "=")
if !ok {
continue
}
meta[key] = val
}
ct, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
if ct == "application/json" {
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var b struct {
Summary, Details, Action, Dedup *string
Meta map[string]string
}
err = json.Unmarshal(data, &b)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if b.Summary != nil {
summary = *b.Summary
}
if b.Details != nil {
details = *b.Details
}
if b.Dedup != nil {
dedup = *b.Dedup
}
if b.Action != nil {
action = *b.Action
}
if b.Meta != nil {
meta = b.Meta
}
}
status := alert.StatusTriggered
if action == "close" {
status = alert.StatusClosed
}
summary = validate.SanitizeText(summary, alert.MaxSummaryLength)
details = validate.SanitizeText(details, alert.MaxDetailsLength)
a := &alert.Alert{
Summary: summary,
Details: details,
Source: alert.SourceGeneric,
ServiceID: serviceID,
Dedup: alert.NewUserDedup(dedup),
Status: status,
}
var resp struct {
AlertID int
ServiceID string
IsNew bool
}
err = retry.DoTemporaryError(func(int) error {
createdAlert, isNew, err := h.c.AlertStore.CreateOrUpdateWithMeta(ctx, a, meta)
if createdAlert != nil {
resp.AlertID = createdAlert.ID
resp.ServiceID = createdAlert.ServiceID
resp.IsNew = isNew
}
return err
},
retry.Log(ctx),
retry.Limit(10),
retry.FibBackoff(time.Second),
)
if errutil.HTTPError(ctx, w, errors.Wrap(err, "create alert")) {
return
}
if r.Header.Get("Accept") != "application/json" {
w.WriteHeader(204)
return
}
data, err := json.Marshal(&resp)
if errutil.HTTPError(ctx, w, err) {
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(data)
}
|