Incidents stay separate until Alertmanager groups their alerts, but a bad
release can break the API, the connection pool and a dozen pods in
different groups, and three months later each incident on its own says
little. An event is the context they share: a release, a change, a
maintenance window or an outage. Incidents attach to it, many to many,
and one of them can be marked as the trigger. Incidents are never merged,
so each keeps its own timeline, assignee and metrics; merging would have
thrown that away and could not be undone.
Nothing attaches by itself. An incident's page and
GET /api/incidents/{id}/related-events suggest events within two hours of
it, and a person decides. Events are team-scoped like incidents, kind is
a closed set (a CHECK constraint, so the UI can colour and filter by it),
and they are hard-deleted: the incidents stay and each one's timeline
records the detach. A repeated external_id returns the event already
recorded, so CI can post a release marker and retry safely. Figures such
as time to first ack and the first alarm to last resolution are computed
when an event is read and never stored.
The web UI gets an Events page and an event page with a merged timeline,
an Events card on the incident, and a tag on queue rows. make dev seeds a
release and a maintenance window.
All of it is additive. Migration 004 only creates tables, so v0.53.1
reads the same database and ignores them. The incident JSON gains
event_count (always present) and events (omitted when empty, so clients
detect support from event_count). terdut-tui keeps working unchanged and
simply does not show events yet; no TUI version is required and none is
excluded. The operator's client is untouched. The Prometheus allowlist, the CSP and the
resource limits do not change.
1068 lines
32 KiB
Go
1068 lines
32 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.ryuvia.com/niklas/terdut-server/internal/models"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// Events are contexts that incidents are attached to: a release, a change, a
|
|
// maintenance window, an outage. They explain incidents without merging them,
|
|
// so every incident keeps its own timeline, assignee and metrics. See
|
|
// docs/events.md.
|
|
|
|
const (
|
|
maxEventTitle = 200
|
|
maxEventSummary = 20000
|
|
maxEventNote = 10000
|
|
maxEventURL = 2000
|
|
maxEventExtID = 200
|
|
|
|
// eventListPreview is how many attached incidents a list row carries.
|
|
eventListPreview = 3
|
|
|
|
// relatedEventWindow is how far from an incident an event may be and still
|
|
// be suggested for it: an event that started up to this long after the
|
|
// incident opened, or that ended (or, with no end, started) up to this long
|
|
// before. A guess for a person to confirm, never an attachment.
|
|
relatedEventWindow = 2 * time.Hour
|
|
)
|
|
|
|
const eventSelectFrom = `
|
|
SELECT e.id, e.team_id, t.name, e.kind, e.title, e.summary, e.started_at, e.ended_at,
|
|
e.source, e.external_id, e.external_url,
|
|
e.created_by_user_id, cu.username, e.created_by_service_account_id, csa.name,
|
|
e.created_at
|
|
FROM events e
|
|
JOIN teams t ON t.id = e.team_id
|
|
LEFT JOIN users cu ON cu.id = e.created_by_user_id
|
|
LEFT JOIN service_accounts csa ON csa.id = e.created_by_service_account_id`
|
|
|
|
func scanEvent(s scanner) (models.Event, error) {
|
|
var e models.Event
|
|
var startedAt, createdAt int64
|
|
var endedAt *int64
|
|
if err := s.Scan(
|
|
&e.ID, &e.TeamID, &e.TeamName, &e.Kind, &e.Title, &e.Summary, &startedAt, &endedAt,
|
|
&e.Source, &e.ExternalID, &e.ExternalURL,
|
|
&e.CreatedByID, &e.CreatedBy, &e.CreatedByServiceAccountID, &e.CreatedByServiceAccount,
|
|
&createdAt,
|
|
); err != nil {
|
|
return e, err
|
|
}
|
|
e.StartedAt = time.Unix(startedAt, 0).UTC()
|
|
e.EndedAt = unixPtr(endedAt)
|
|
e.CreatedAt = time.Unix(createdAt, 0).UTC()
|
|
return e, nil
|
|
}
|
|
|
|
func fetchEvent(ctx context.Context, q querier, id int64) (models.Event, error) {
|
|
return scanEvent(q.QueryRowContext(ctx, eventSelectFrom+" WHERE e.id = $1", id))
|
|
}
|
|
|
|
// loadEventIncidents returns the incidents attached to each of the events,
|
|
// trigger first and then in the order they opened.
|
|
func loadEventIncidents(ctx context.Context, q querier, eventIDs []int64) (map[int64][]models.EventIncident, error) {
|
|
out := make(map[int64][]models.EventIncident, len(eventIDs))
|
|
if len(eventIDs) == 0 {
|
|
return out, nil
|
|
}
|
|
rows, err := q.QueryContext(ctx, `
|
|
SELECT ei.event_id, i.id, i.title, i.status, i.severity, i.triggered_at,
|
|
i.acknowledged_at, i.resolved_at, ei.is_trigger, ei.attached_at
|
|
FROM event_incidents ei
|
|
JOIN incidents i ON i.id = ei.incident_id
|
|
WHERE ei.event_id = ANY($1)
|
|
ORDER BY ei.event_id, ei.is_trigger DESC, i.triggered_at ASC, i.id ASC`, eventIDs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var eventID, triggeredAt, attachedAt int64
|
|
var ackAt, resolvedAt *int64
|
|
var ei models.EventIncident
|
|
if err := rows.Scan(&eventID, &ei.IncidentID, &ei.Title, &ei.Status, &ei.Severity, &triggeredAt,
|
|
&ackAt, &resolvedAt, &ei.IsTrigger, &attachedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
ei.TriggeredAt = time.Unix(triggeredAt, 0).UTC()
|
|
ei.AcknowledgedAt = unixPtr(ackAt)
|
|
ei.ResolvedAt = unixPtr(resolvedAt)
|
|
ei.AttachedAt = time.Unix(attachedAt, 0).UTC()
|
|
out[eventID] = append(out[eventID], ei)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// applyEventIncidents fills in the figures derived from an event's incidents.
|
|
// preview caps how many of them are listed on the event; 0 lists all.
|
|
func applyEventIncidents(e *models.Event, incs []models.EventIncident, preview int) {
|
|
e.IncidentCount = len(incs)
|
|
e.OpenIncidentCount = 0
|
|
e.WorstSeverity, e.FirstTriggeredAt, e.TimeToFirstAckSeconds = nil, nil, nil
|
|
e.AllResolvedAt, e.SpanSeconds = nil, nil
|
|
|
|
var first, firstAck, lastResolved *time.Time
|
|
worst := ""
|
|
for i := range incs {
|
|
inc := &incs[i]
|
|
if inc.ResolvedAt == nil {
|
|
e.OpenIncidentCount++
|
|
} else if lastResolved == nil || inc.ResolvedAt.After(*lastResolved) {
|
|
lastResolved = inc.ResolvedAt
|
|
}
|
|
if first == nil || inc.TriggeredAt.Before(*first) {
|
|
first = &inc.TriggeredAt
|
|
}
|
|
if inc.AcknowledgedAt != nil && (firstAck == nil || inc.AcknowledgedAt.Before(*firstAck)) {
|
|
firstAck = inc.AcknowledgedAt
|
|
}
|
|
if inc.Severity != nil && severityRank(*inc.Severity) > severityRank(worst) {
|
|
worst = *inc.Severity
|
|
}
|
|
}
|
|
if worst != "" {
|
|
e.WorstSeverity = &worst
|
|
}
|
|
if first != nil {
|
|
t := *first
|
|
e.FirstTriggeredAt = &t
|
|
if firstAck != nil {
|
|
secs := int64(firstAck.Sub(t).Seconds())
|
|
if secs < 0 {
|
|
secs = 0
|
|
}
|
|
e.TimeToFirstAckSeconds = &secs
|
|
}
|
|
if e.OpenIncidentCount == 0 && lastResolved != nil {
|
|
r := *lastResolved
|
|
e.AllResolvedAt = &r
|
|
secs := int64(r.Sub(t).Seconds())
|
|
e.SpanSeconds = &secs
|
|
}
|
|
}
|
|
|
|
if preview > 0 && len(incs) > preview {
|
|
incs = incs[:preview]
|
|
}
|
|
e.Incidents = incs
|
|
}
|
|
|
|
// queryEvents runs an event list query. where and order are SQL fragments the
|
|
// caller built with args; the events come back with their derived figures and
|
|
// the first eventListPreview attached incidents.
|
|
func queryEvents(ctx context.Context, q querier, where []string, args *sqlArgs, order string, limit int) ([]models.Event, error) {
|
|
rows, err := q.QueryContext(ctx,
|
|
fmt.Sprintf("%s WHERE %s ORDER BY %s LIMIT %s",
|
|
eventSelectFrom, strings.Join(where, " AND "), order, args.add(limit)),
|
|
args.all()...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
events := []models.Event{}
|
|
ids := []int64{}
|
|
for rows.Next() {
|
|
e, err := scanEvent(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
events = append(events, e)
|
|
ids = append(ids, e.ID)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
rows.Close()
|
|
|
|
byEvent, err := loadEventIncidents(ctx, q, ids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range events {
|
|
applyEventIncidents(&events[i], byEvent[events[i].ID], eventListPreview)
|
|
}
|
|
return events, nil
|
|
}
|
|
|
|
// fetchEventDetail is one event with every attached incident.
|
|
func fetchEventDetail(ctx context.Context, q querier, id int64) (models.Event, error) {
|
|
e, err := fetchEvent(ctx, q, id)
|
|
if err != nil {
|
|
return e, err
|
|
}
|
|
byEvent, err := loadEventIncidents(ctx, q, []int64{id})
|
|
if err != nil {
|
|
return e, err
|
|
}
|
|
applyEventIncidents(&e, byEvent[id], 0)
|
|
return e, nil
|
|
}
|
|
|
|
// eventIDParam reads {id} and confirms the event belongs to a team the caller is
|
|
// in, answering 404 otherwise, for the same reason incidentIDParam does. It
|
|
// returns the event's team.
|
|
func eventIDParam(w http.ResponseWriter, r *http.Request, db *sql.DB) (id, teamID int64, ok bool) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid event id"))
|
|
return 0, 0, false
|
|
}
|
|
err = db.QueryRowContext(r.Context(),
|
|
"SELECT team_id FROM events WHERE id = $1 AND team_id = ANY($2)",
|
|
id, callerTeamIDs(r.Context())).Scan(&teamID)
|
|
if err == sql.ErrNoRows {
|
|
respond(w, http.StatusNotFound, errResp("event not found"))
|
|
return 0, 0, false
|
|
}
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return 0, 0, false
|
|
}
|
|
return id, teamID, true
|
|
}
|
|
|
|
// validateEventURL accepts only http(s) links: the web UI renders the value as
|
|
// an anchor, and a javascript: URL there would run in a viewer's session.
|
|
func validateEventURL(s string) bool {
|
|
if len(s) > maxEventURL {
|
|
return false
|
|
}
|
|
u, err := url.Parse(s)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
|
|
}
|
|
|
|
// escapeLike makes s safe to embed in an ILIKE pattern.
|
|
func escapeLike(s string) string {
|
|
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Events
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// handleListEvents answers GET /api/events: the events of the caller's teams,
|
|
// newest first.
|
|
func handleListEvents(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
args := &sqlArgs{}
|
|
where := []string{"e.team_id = ANY(" + args.add(callerTeamIDs(r.Context())) + ")"}
|
|
|
|
if team := q.Get("team_id"); team != "" {
|
|
if n, err := strconv.ParseInt(team, 10, 64); err == nil {
|
|
where = append(where, "e.team_id = "+args.add(n))
|
|
}
|
|
}
|
|
if kind := q.Get("kind"); kind != "" {
|
|
if !models.ValidEventKind(kind) {
|
|
respond(w, http.StatusBadRequest, errResp("invalid kind"))
|
|
return
|
|
}
|
|
where = append(where, "e.kind = "+args.add(kind))
|
|
}
|
|
if from := q.Get("from"); from != "" {
|
|
if t, err := time.Parse("2006-01-02", from); err == nil {
|
|
where = append(where, "e.started_at >= "+args.add(t.UTC().Unix()))
|
|
}
|
|
}
|
|
if to := q.Get("to"); to != "" {
|
|
if t, err := time.Parse("2006-01-02", to); err == nil {
|
|
where = append(where, "e.started_at < "+args.add(t.UTC().AddDate(0, 0, 1).Unix()))
|
|
}
|
|
}
|
|
switch q.Get("has_incidents") {
|
|
case "true":
|
|
where = append(where, "EXISTS (SELECT 1 FROM event_incidents ei WHERE ei.event_id = e.id)")
|
|
case "false":
|
|
where = append(where, "NOT EXISTS (SELECT 1 FROM event_incidents ei WHERE ei.event_id = e.id)")
|
|
}
|
|
if text := strings.TrimSpace(q.Get("q")); text != "" {
|
|
where = append(where, "e.title ILIKE '%' || "+args.add(escapeLike(text))+" || '%'")
|
|
}
|
|
|
|
limit := 50
|
|
if l := q.Get("limit"); l != "" {
|
|
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 500 {
|
|
limit = n
|
|
}
|
|
}
|
|
|
|
events, err := queryEvents(r.Context(), db, where, args, "e.started_at DESC, e.id DESC", limit)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, events)
|
|
}
|
|
}
|
|
|
|
// handleCreateEvent answers POST /api/events. A repeated external_id in the same
|
|
// team returns the event already recorded under it (200) rather than a second
|
|
// one, so a CI job can retry safely.
|
|
func handleCreateEvent(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
TeamID int64 `json:"team_id"`
|
|
Kind string `json:"kind"`
|
|
Title string `json:"title"`
|
|
Summary string `json:"summary"`
|
|
StartedAt *time.Time `json:"started_at"`
|
|
EndedAt *time.Time `json:"ended_at"`
|
|
ExternalID string `json:"external_id"`
|
|
ExternalURL string `json:"external_url"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
if req.TeamID <= 0 {
|
|
respond(w, http.StatusBadRequest, errResp("team_id is required"))
|
|
return
|
|
}
|
|
if !requireTeamMember(w, r, req.TeamID) {
|
|
return
|
|
}
|
|
title := strings.TrimSpace(req.Title)
|
|
switch {
|
|
case !models.ValidEventKind(req.Kind):
|
|
respond(w, http.StatusBadRequest, errResp("kind must be release, change, maintenance, outage or other"))
|
|
return
|
|
case title == "":
|
|
respond(w, http.StatusBadRequest, errResp("title is required"))
|
|
return
|
|
case len(title) > maxEventTitle:
|
|
respond(w, http.StatusBadRequest, errResp("title is too long"))
|
|
return
|
|
case len(req.Summary) > maxEventSummary:
|
|
respond(w, http.StatusBadRequest, errResp("summary is too long"))
|
|
return
|
|
case len(req.ExternalID) > maxEventExtID:
|
|
respond(w, http.StatusBadRequest, errResp("external_id is too long"))
|
|
return
|
|
case req.ExternalURL != "" && !validateEventURL(req.ExternalURL):
|
|
respond(w, http.StatusBadRequest, errResp("external_url must be an http or https URL"))
|
|
return
|
|
}
|
|
|
|
started := time.Now().Unix()
|
|
if req.StartedAt != nil {
|
|
started = req.StartedAt.Unix()
|
|
}
|
|
var ended *int64
|
|
if req.EndedAt != nil {
|
|
e := req.EndedAt.Unix()
|
|
if e < started {
|
|
respond(w, http.StatusBadRequest, errResp("ended_at is before started_at"))
|
|
return
|
|
}
|
|
ended = &e
|
|
}
|
|
|
|
source := models.EventSourceAPI
|
|
if caller, _ := callerFromContext(r.Context()); caller.user != nil {
|
|
source = models.EventSourceManual
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
|
|
var externalID, externalURL *string
|
|
if req.ExternalID != "" {
|
|
externalID = &req.ExternalID
|
|
}
|
|
if req.ExternalURL != "" {
|
|
externalURL = &req.ExternalURL
|
|
}
|
|
|
|
var id int64
|
|
err := db.QueryRowContext(r.Context(), `
|
|
INSERT INTO events (team_id, kind, title, summary, started_at, ended_at, source,
|
|
external_id, external_url, created_by_user_id, created_by_service_account_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
|
ON CONFLICT (team_id, external_id) WHERE external_id IS NOT NULL DO NOTHING
|
|
RETURNING id`,
|
|
req.TeamID, req.Kind, title, req.Summary, started, ended, source,
|
|
externalID, externalURL, userID, saID).Scan(&id)
|
|
status := http.StatusCreated
|
|
if err == sql.ErrNoRows {
|
|
// The external_id was already recorded: hand back that event.
|
|
status = http.StatusOK
|
|
err = db.QueryRowContext(r.Context(),
|
|
"SELECT id FROM events WHERE team_id = $1 AND external_id = $2",
|
|
req.TeamID, req.ExternalID).Scan(&id)
|
|
}
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
e, err := fetchEventDetail(r.Context(), db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, status, e)
|
|
}
|
|
}
|
|
|
|
func handleGetEvent(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
e, err := fetchEventDetail(r.Context(), db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, e)
|
|
}
|
|
}
|
|
|
|
// handleUpdateEvent answers PATCH /api/events/{id}. Absent fields stay as they
|
|
// are; ended_at and external_url take null to clear. external_id and team_id
|
|
// are fixed when the event is created.
|
|
func handleUpdateEvent(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req struct {
|
|
Kind *string `json:"kind"`
|
|
Title *string `json:"title"`
|
|
Summary *string `json:"summary"`
|
|
StartedAt *time.Time `json:"started_at"`
|
|
EndedAt json.RawMessage `json:"ended_at"`
|
|
ExternalURL json.RawMessage `json:"external_url"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
|
|
cur, err := fetchEvent(r.Context(), db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
kind, title, summary := cur.Kind, cur.Title, cur.Summary
|
|
started, ended := cur.StartedAt, cur.EndedAt
|
|
extURL := cur.ExternalURL
|
|
|
|
if req.Kind != nil {
|
|
if !models.ValidEventKind(*req.Kind) {
|
|
respond(w, http.StatusBadRequest, errResp("kind must be release, change, maintenance, outage or other"))
|
|
return
|
|
}
|
|
kind = *req.Kind
|
|
}
|
|
if req.Title != nil {
|
|
title = strings.TrimSpace(*req.Title)
|
|
if title == "" || len(title) > maxEventTitle {
|
|
respond(w, http.StatusBadRequest, errResp("title must be 1 to 200 characters"))
|
|
return
|
|
}
|
|
}
|
|
if req.Summary != nil {
|
|
if len(*req.Summary) > maxEventSummary {
|
|
respond(w, http.StatusBadRequest, errResp("summary is too long"))
|
|
return
|
|
}
|
|
summary = *req.Summary
|
|
}
|
|
if req.StartedAt != nil {
|
|
started = req.StartedAt.UTC()
|
|
}
|
|
if req.EndedAt != nil {
|
|
if string(req.EndedAt) == "null" {
|
|
ended = nil
|
|
} else {
|
|
var t time.Time
|
|
if err := json.Unmarshal(req.EndedAt, &t); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("ended_at must be an RFC 3339 timestamp or null"))
|
|
return
|
|
}
|
|
t = t.UTC()
|
|
ended = &t
|
|
}
|
|
}
|
|
if ended != nil && ended.Before(started) {
|
|
respond(w, http.StatusBadRequest, errResp("ended_at is before started_at"))
|
|
return
|
|
}
|
|
if req.ExternalURL != nil {
|
|
if string(req.ExternalURL) == "null" {
|
|
extURL = nil
|
|
} else {
|
|
var s string
|
|
if err := json.Unmarshal(req.ExternalURL, &s); err != nil || !validateEventURL(s) {
|
|
respond(w, http.StatusBadRequest, errResp("external_url must be an http or https URL or null"))
|
|
return
|
|
}
|
|
extURL = &s
|
|
}
|
|
}
|
|
|
|
var endedUnix *int64
|
|
if ended != nil {
|
|
e := ended.Unix()
|
|
endedUnix = &e
|
|
}
|
|
if _, err := db.ExecContext(r.Context(), `
|
|
UPDATE events SET kind = $2, title = $3, summary = $4, started_at = $5,
|
|
ended_at = $6, external_url = $7
|
|
WHERE id = $1`,
|
|
id, kind, title, summary, started.Unix(), endedUnix, extURL); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
e, err := fetchEventDetail(r.Context(), db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, e)
|
|
}
|
|
}
|
|
|
|
// handleDeleteEvent answers DELETE /api/events/{id}. The event is gone for good,
|
|
// with its links and notes; the incidents stay, and each one's timeline records
|
|
// that it was detached. Team owners only.
|
|
func handleDeleteEvent(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, teamID, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
if !requireTeamOwner(w, r, teamID) {
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
|
|
tx, err := db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck
|
|
|
|
if _, err := tx.ExecContext(r.Context(), `
|
|
INSERT INTO incident_events (incident_id, type, user_id, service_account_id, detail, created_at)
|
|
SELECT ei.incident_id, $2, $3, $4, e.title || ' (event deleted)', $5
|
|
FROM event_incidents ei
|
|
JOIN events e ON e.id = ei.event_id
|
|
WHERE ei.event_id = $1`,
|
|
id, evEventDetached, userID, saID, time.Now().Unix()); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(), "DELETE FROM events WHERE id = $1", id); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Timeline and notes
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// timelineSkipTypes are incident timeline events left out of an event's merged
|
|
// timeline: delivery bookkeeping and per-alert churn that would bury the story,
|
|
// and the attach/detach records, which the event's own incident list already
|
|
// shows. Each incident's own timeline still has all of them.
|
|
var timelineSkipTypes = []string{"notified", "notify_failed", evAlertAdded, evAlertResolved, evEventAttached, evEventDetached}
|
|
|
|
func handleEventTimeline(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
ctx := r.Context()
|
|
ev, err := fetchEvent(ctx, db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
entries := []models.EventTimelineEntry{{Source: "event", Type: "started", CreatedAt: ev.StartedAt}}
|
|
if ev.EndedAt != nil {
|
|
entries = append(entries, models.EventTimelineEntry{Source: "event", Type: "ended", CreatedAt: *ev.EndedAt})
|
|
}
|
|
|
|
noteRows, err := db.QueryContext(ctx, `
|
|
SELECT n.id, n.content, n.user_id, u.username, n.service_account_id, sa.name, n.created_at
|
|
FROM event_notes n
|
|
LEFT JOIN users u ON u.id = n.user_id
|
|
LEFT JOIN service_accounts sa ON sa.id = n.service_account_id
|
|
WHERE n.event_id = $1`, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer noteRows.Close()
|
|
for noteRows.Next() {
|
|
e := models.EventTimelineEntry{Source: "event", Type: "note"}
|
|
var content string
|
|
var ts int64
|
|
if err := noteRows.Scan(&e.ID, &content, &e.UserID, &e.Username,
|
|
&e.ServiceAccountID, &e.ServiceAccountName, &ts); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
e.Detail = &content
|
|
e.CreatedAt = time.Unix(ts, 0).UTC()
|
|
entries = append(entries, e)
|
|
}
|
|
if err := noteRows.Err(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
noteRows.Close()
|
|
|
|
incRows, err := db.QueryContext(ctx, `
|
|
SELECT e.id, e.incident_id, i.title, e.type, e.user_id, u.username,
|
|
e.service_account_id, sa.name, e.detail, e.created_at
|
|
FROM event_incidents ei
|
|
JOIN incidents i ON i.id = ei.incident_id
|
|
JOIN incident_events e ON e.incident_id = i.id
|
|
LEFT JOIN users u ON u.id = e.user_id
|
|
LEFT JOIN service_accounts sa ON sa.id = e.service_account_id
|
|
WHERE ei.event_id = $1 AND e.type <> ALL($2)`, id, timelineSkipTypes)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer incRows.Close()
|
|
for incRows.Next() {
|
|
e := models.EventTimelineEntry{Source: "incident"}
|
|
var ts int64
|
|
if err := incRows.Scan(&e.ID, &e.IncidentID, &e.IncidentTitle, &e.Type, &e.UserID, &e.Username,
|
|
&e.ServiceAccountID, &e.ServiceAccountName, &e.Detail, &ts); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
e.CreatedAt = time.Unix(ts, 0).UTC()
|
|
entries = append(entries, e)
|
|
}
|
|
if err := incRows.Err(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
// Chronological; at the same second the event's own lines come first
|
|
// (a release starts before the alarms it caused), then by id.
|
|
sort.SliceStable(entries, func(i, j int) bool {
|
|
a, b := entries[i], entries[j]
|
|
if !a.CreatedAt.Equal(b.CreatedAt) {
|
|
return a.CreatedAt.Before(b.CreatedAt)
|
|
}
|
|
if a.Source != b.Source {
|
|
return a.Source == "event"
|
|
}
|
|
return a.ID < b.ID
|
|
})
|
|
respond(w, http.StatusOK, entries)
|
|
}
|
|
}
|
|
|
|
func handleCreateEventNote(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req struct {
|
|
Content string `json:"content"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
if strings.TrimSpace(req.Content) == "" {
|
|
respond(w, http.StatusBadRequest, errResp("content is required"))
|
|
return
|
|
}
|
|
if len(req.Content) > maxEventNote {
|
|
respond(w, http.StatusBadRequest, errResp("content is too long"))
|
|
return
|
|
}
|
|
|
|
caller, _ := callerFromContext(r.Context())
|
|
userID, saID := callerActorIDs(r.Context())
|
|
now := time.Now()
|
|
note := models.EventNote{EventID: id, Content: req.Content, CreatedAt: now.UTC().Truncate(time.Second)}
|
|
if err := db.QueryRowContext(r.Context(), `
|
|
INSERT INTO event_notes (event_id, content, user_id, service_account_id, created_at)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
RETURNING id`, id, req.Content, userID, saID, now.Unix()).Scan(¬e.ID); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if u, ok := caller.AsHuman(); ok {
|
|
note.UserID, note.Username = &u.ID, &u.Username
|
|
} else if name, ok := caller.ServiceAccountName(); ok {
|
|
note.ServiceAccountID, note.ServiceAccountName = saID, &name
|
|
}
|
|
respond(w, http.StatusCreated, note)
|
|
}
|
|
}
|
|
|
|
// handleDeleteEventNote removes one of the caller's own notes.
|
|
func handleDeleteEventNote(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
noteID, err := strconv.ParseInt(chi.URLParam(r, "noteID"), 10, 64)
|
|
if err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid note id"))
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
res, err := db.ExecContext(r.Context(), `
|
|
DELETE FROM event_notes
|
|
WHERE id = $1 AND event_id = $2 AND (user_id = $3 OR service_account_id = $4)`,
|
|
noteID, id, userID, saID)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
respond(w, http.StatusNotFound, errResp("note not found"))
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Attaching incidents
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Per-incident outcomes of an attach.
|
|
const (
|
|
attachOK = "ok" // attached now
|
|
attachNoop = "noop" // already attached
|
|
attachNotFound = "not_found" // no such incident, or not one of the caller's teams
|
|
attachTeamMismatch = "team_mismatch" // an incident of another of the caller's teams
|
|
)
|
|
|
|
type attachResult struct {
|
|
ID int64 `json:"id"`
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
// handleAttachIncidents answers POST /api/events/{id}/incidents. Each incident
|
|
// gets its own outcome, so one that cannot be attached does not hold up the
|
|
// rest; the request as a whole is one transaction, so a database error leaves
|
|
// nothing half-applied.
|
|
func handleAttachIncidents(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, teamID, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req struct {
|
|
IncidentIDs []int64 `json:"incident_ids"`
|
|
// TriggerIncidentID, when set, makes that incident the event's
|
|
// trigger. It must be attached by this request or earlier.
|
|
TriggerIncidentID *int64 `json:"trigger_incident_id"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IncidentIDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
teams := callerTeamIDs(ctx)
|
|
userID, saID := callerActorIDs(ctx)
|
|
now := time.Now().Unix()
|
|
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck
|
|
|
|
var title string
|
|
if err := tx.QueryRowContext(ctx, "SELECT title FROM events WHERE id = $1", id).Scan(&title); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
results := make([]attachResult, 0, len(ids))
|
|
summary := map[string]int{attachOK: 0, attachNoop: 0, attachNotFound: 0, attachTeamMismatch: 0}
|
|
for _, incID := range ids {
|
|
var incTeam int64
|
|
err := tx.QueryRowContext(ctx,
|
|
"SELECT team_id FROM incidents WHERE id = $1 AND team_id = ANY($2)", incID, teams).Scan(&incTeam)
|
|
status := attachOK
|
|
switch {
|
|
case err == sql.ErrNoRows:
|
|
status = attachNotFound
|
|
case err != nil:
|
|
serverError(w, r, err)
|
|
return
|
|
case incTeam != teamID:
|
|
status = attachTeamMismatch
|
|
default:
|
|
res, err := tx.ExecContext(ctx, `
|
|
INSERT INTO event_incidents (event_id, incident_id, attached_at, attached_by_user_id, attached_by_service_account_id)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
ON CONFLICT (event_id, incident_id) DO NOTHING`, id, incID, now, userID, saID)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
status = attachNoop
|
|
} else if err := logEvent(ctx, tx, incID, evEventAttached, userID, saID, nil, &title); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
}
|
|
results = append(results, attachResult{ID: incID, Status: status})
|
|
summary[status]++
|
|
}
|
|
|
|
if req.TriggerIncidentID != nil {
|
|
set, err := setEventTrigger(ctx, tx, id, req.TriggerIncidentID)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if !set {
|
|
respond(w, http.StatusBadRequest, errResp("trigger_incident_id is not attached to this event"))
|
|
return
|
|
}
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
e, err := fetchEventDetail(ctx, db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, struct {
|
|
Results []attachResult `json:"results"`
|
|
Summary map[string]int `json:"summary"`
|
|
Event models.Event `json:"event"`
|
|
}{results, summary, e})
|
|
}
|
|
}
|
|
|
|
// setEventTrigger makes incidentID the event's one trigger, or clears the
|
|
// trigger when it is nil. It reports false when incidentID is not attached.
|
|
func setEventTrigger(ctx context.Context, q querier, eventID int64, incidentID *int64) (bool, error) {
|
|
// Clear first: the partial unique index allows one trigger per event.
|
|
if _, err := q.ExecContext(ctx,
|
|
"UPDATE event_incidents SET is_trigger = false WHERE event_id = $1 AND is_trigger", eventID); err != nil {
|
|
return false, err
|
|
}
|
|
if incidentID == nil {
|
|
return true, nil
|
|
}
|
|
res, err := q.ExecContext(ctx,
|
|
"UPDATE event_incidents SET is_trigger = true WHERE event_id = $1 AND incident_id = $2",
|
|
eventID, *incidentID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return n > 0, nil
|
|
}
|
|
|
|
func handleDetachIncident(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
incID, err := strconv.ParseInt(chi.URLParam(r, "incidentID"), 10, 64)
|
|
if err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid incident id"))
|
|
return
|
|
}
|
|
ctx := r.Context()
|
|
userID, saID := callerActorIDs(ctx)
|
|
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck
|
|
|
|
var title string
|
|
err = tx.QueryRowContext(ctx, `
|
|
DELETE FROM event_incidents ei
|
|
USING events e
|
|
WHERE ei.event_id = $1 AND ei.incident_id = $2 AND e.id = ei.event_id
|
|
RETURNING e.title`, id, incID).Scan(&title)
|
|
if err == sql.ErrNoRows {
|
|
respond(w, http.StatusNotFound, errResp("incident is not attached to this event"))
|
|
return
|
|
}
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if err := logEvent(ctx, tx, incID, evEventDetached, userID, saID, nil, &title); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// handleSetEventTrigger answers PUT /api/events/{id}/trigger with
|
|
// {"incident_id": N}, or {"incident_id": null} to clear it.
|
|
func handleSetEventTrigger(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, ok := eventIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req struct {
|
|
IncidentID *int64 `json:"incident_id"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
tx, err := db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck
|
|
set, err := setEventTrigger(r.Context(), tx, id, req.IncidentID)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
if !set {
|
|
respond(w, http.StatusNotFound, errResp("incident is not attached to this event"))
|
|
return
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
e, err := fetchEventDetail(r.Context(), db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, e)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// From the incident's side
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// incidentEventRefs lists the events an incident is attached to, newest first.
|
|
func incidentEventRefs(ctx context.Context, q querier, incidentID int64) ([]models.IncidentEventRef, error) {
|
|
rows, err := q.QueryContext(ctx, `
|
|
SELECT e.id, e.kind, e.title, e.started_at, ei.is_trigger
|
|
FROM event_incidents ei
|
|
JOIN events e ON e.id = ei.event_id
|
|
WHERE ei.incident_id = $1
|
|
ORDER BY e.started_at DESC, e.id DESC`, incidentID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
refs := []models.IncidentEventRef{}
|
|
for rows.Next() {
|
|
var ref models.IncidentEventRef
|
|
var ts int64
|
|
if err := rows.Scan(&ref.ID, &ref.Kind, &ref.Title, &ts, &ref.IsTrigger); err != nil {
|
|
return nil, err
|
|
}
|
|
ref.StartedAt = time.Unix(ts, 0).UTC()
|
|
refs = append(refs, ref)
|
|
}
|
|
return refs, rows.Err()
|
|
}
|
|
|
|
// handleIncidentRelatedEvents answers GET /api/incidents/{id}/related-events:
|
|
// events of the incident's team that are close in time to it and not yet
|
|
// attached, nearest first. A plain time-window query; it attaches nothing.
|
|
func handleIncidentRelatedEvents(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, ok := incidentIDParam(w, r, db)
|
|
if !ok {
|
|
return
|
|
}
|
|
var teamID, triggeredAt int64
|
|
if err := db.QueryRowContext(r.Context(),
|
|
"SELECT team_id, triggered_at FROM incidents WHERE id = $1", id).Scan(&teamID, &triggeredAt); err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
limit := 5
|
|
if l := r.URL.Query().Get("limit"); l != "" {
|
|
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 20 {
|
|
limit = n
|
|
}
|
|
}
|
|
|
|
window := int64(relatedEventWindow.Seconds())
|
|
args := &sqlArgs{}
|
|
trig := args.add(triggeredAt) + "::bigint"
|
|
w2 := args.add(window) + "::bigint"
|
|
where := []string{
|
|
"e.team_id = " + args.add(teamID),
|
|
"NOT EXISTS (SELECT 1 FROM event_incidents ei WHERE ei.event_id = e.id AND ei.incident_id = " + args.add(id) + ")",
|
|
"e.started_at <= " + trig + " + " + w2,
|
|
"COALESCE(e.ended_at, e.started_at) + " + w2 + " >= " + trig,
|
|
}
|
|
events, err := queryEvents(r.Context(), db, where, args,
|
|
"abs(e.started_at - "+trig+") ASC, e.id DESC", limit)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, events)
|
|
}
|
|
}
|