Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 12 additions & 102 deletions cmd/levelrail-cli/apps_alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func appsAlertsUsage(prog string) string {
%[1]s apps alerts create <app> --kind slo_burn --slo 99.9 [--slo-latency-ms N] [flags]
%[1]s apps alerts slo <app> [--slo 99.9] [--slo-latency-ms N]
%[1]s apps alerts template <app> [--profile-type web|worker|database] [--channel ID]
%[1]s apps alerts update <app> <id> --kind KIND [flags]
%[1]s apps alerts update <app> <id> [flags]
%[1]s apps alerts delete <app> <id> [flags]

Manages an app's alert rules. A threshold rule watches a metric; a
Expand Down Expand Up @@ -462,114 +462,24 @@ Flags:
`, prog, apiTokenEnvHelp, apiURLEnvHelp, defaultAPIURL)
}

// Full replace: every field the rule keeps must be passed again, there is no partial update.
func runAppsAlertsUpdate(prog string, args []string, stdout, stderr io.Writer, lookupEnv func(string) (string, bool)) int {
fs, tokenFlagP, apiURLFlagP, profileFlagP, jsonOutP, outputFlagP, queryFlagP := apiFlagSet(prog, "apps alerts update", "print the updated rule as JSON to stdout and nothing else", stderr)
var (
name, kind, metric, comparator, forDuration string
threshold float64
restartCountThreshold int
restartWindow string
scheduledTaskID string
channelID, notifyURL, notifyKind string
disabled bool
)
fs.StringVar(&name, "name", "", "display name for the rule (required)")
fs.StringVar(&kind, "kind", "", "rule kind: threshold, crashloop, cert_expiry, cert_expiring, cert_renewal_stalled, patch_status, scheduled_task_failure, node_disk_space, node_resource_usage, domain_health, domain_not_resolving, domain_traffic_drop, parked_domain_cert_expiry, domain_registration_expiry, backup_missing, node_offline, node_cert_expiring, control_plane_backup_stale, log_archive_stale, export_behind, backup_copy_behind, audit_chain_broken, backup_size_anomaly, deploy_duration_regression, slo_burn (required)")
fs.StringVar(&metric, "metric", "", "metric name (--kind threshold only, required for that kind)")
fs.StringVar(&comparator, "comparator", "", "one of >, <, >=, <= (--kind threshold only, required for that kind)")
fs.Float64Var(&threshold, "threshold", 0, "threshold value (--kind threshold), or days for --kind cert_expiring (default 14)")
fs.StringVar(&forDuration, "for-duration", "", "how long the condition must hold before firing, e.g. \"2m\" (--kind threshold or domain_health only, optional); for --kind backup_missing, the overdue grace period, e.g. \"6h\" (optional, defaults to 6h)")
fs.IntVar(&restartCountThreshold, "restart-count-threshold", 0, "restart count (--kind crashloop) or consecutive-failure count (--kind scheduled_task_failure) that triggers firing, required for both kinds")
fs.StringVar(&restartWindow, "restart-window", "", "time window restarts are counted in, e.g. \"5m\" (--kind crashloop only, required for that kind)")
fs.StringVar(&scheduledTaskID, "scheduled-task-id", "", "which of this app's scheduled tasks to watch (--kind scheduled_task_failure only, required for that kind; see \"apps scheduled-tasks list\")")
backupResourceKindP, backupDatabaseNameP, backupVolumeNameP := registerBackupMissingFlags(fs)
fs.StringVar(&channelID, "channel-id", "", "attach an already-connected notification channel (see \"channels list\")")
fs.StringVar(&notifyURL, "notify-url", "", "legacy alternative to --channel-id: a raw webhook URL/destination")
fs.StringVar(&notifyKind, "notify-kind", "", "legacy alternative to --channel-id: generic, slack, discord, telegram, email, pushover, pagerduty, teams, resend, ntfy, gotify, mattermost, lark, rocketchat, opsgenie, webex, googlechat, matrix, zulip")
fs.BoolVar(&disabled, "disabled", false, "leave the rule disabled (default: enabled)")
noise := registerAlertNoiseFlags(fs)
slo := registerSLOFlags(fs)
fs.Usage = func() { _, _ = fmt.Fprint(stderr, appsAlertsUpdateUsage(prog)) }

tokenFlag, apiURLFlag, profileFlag, jsonOut, of, exitCode, ok := parseAPIFlags(fs, args, apiFlagPtrs{tokenFlagP, apiURLFlagP, profileFlagP, jsonOutP, outputFlagP, queryFlagP}, prog, stderr)
if !ok {
return exitCode
}

rest, argsOK := requireArgs(fs, stderr, prog, "apps alerts update", "an app name and a rule id", 2)
if !argsOK {
return exitUsage
}
appName, id := rest[0], rest[1]

if name == "" {
return reportError(stdout, stderr, jsonOut, newValidationError("--name is required"))
}
if err := validateAppsAlertsCreateKind(kind, metric, comparator, restartCountThreshold, restartWindow, scheduledTaskID, *backupResourceKindP, *backupDatabaseNameP, *backupVolumeNameP); err != nil {
return reportError(stdout, stderr, jsonOut, err)
}

backupFields := resolveBackupMissingRequestFields(kind, appName, *backupResourceKindP, *backupDatabaseNameP, *backupVolumeNameP)
req := updateAlertRuleRequest{
Name: name, Kind: kind, Metric: metric, Comparator: comparator, Threshold: threshold, ForDuration: forDuration,
RestartCountThreshold: restartCountThreshold, RestartWindow: restartWindow, ScheduledTaskID: scheduledTaskID,
ChannelID: channelID, NotifyURL: notifyURL, NotifyKind: notifyKind,
Enabled: !disabled,
BackupResourceKind: backupFields.ResourceKind, BackupDatabaseName: backupFields.DatabaseName,
BackupServiceName: backupFields.ServiceName, BackupVolumeName: backupFields.VolumeName,
}

if err := noise.apply(&req); err != nil {
return reportError(stdout, stderr, jsonOut, err)
}
if err := slo.apply(kind, &req); err != nil {
return reportError(stdout, stderr, jsonOut, err)
}

client := apiClientFromFlags(prog, apiURLFlag, tokenFlag, profileFlag, lookupEnv)
updated, err := client.UpdateAlertRule(context.Background(), appName, id, req)
if err != nil {
return reportError(stdout, stderr, jsonOut, fmt.Errorf("update alert rule %q for app %q: %w", id, appName, err))
}

if err := renderResult(stdout, of.Format, of.Query, updated, func() {
_, _ = fmt.Fprintf(stdout, "alert rule %q (id %s, kind %s) updated for app %q\n", updated.Name, updated.ID, updated.Kind, appName)
}); err != nil {
_, _ = fmt.Fprintln(stderr, err)
return exitCodeForError(err)
}
return exitOK
}

func appsAlertsUpdateUsage(prog string) string {
return fmt.Sprintf(`Usage:
%[1]s apps alerts update <app> <id> --name NAME --kind threshold --metric METRIC --comparator OP --threshold N [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind crashloop --restart-count-threshold N --restart-window DURATION [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind cert_expiry [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind patch_status [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind scheduled_task_failure --scheduled-task-id ID --restart-count-threshold N [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind node_disk_space [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind node_resource_usage [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind domain_health [flags]
%[1]s apps alerts update <app> <id> --name NAME --kind backup_missing --backup-resource-kind database --backup-database-name NAME [flags]

Fully replaces an existing alert rule's configuration: every flag you
want kept must be passed again on this call, the same convention
"registry-credentials update" uses. Fixing a typo'd --notify-url or
adjusting a --threshold no longer requires deleting and recreating the
rule (which would also drop its notification delivery history). Accepts
the exact same flags as "apps alerts create"; see that command's own
help for what each kind needs.
%[1]s apps alerts update <app> <id> [flags]

Changes an existing alert rule in place, keeping its id and delivery
history. Only the flags you pass change; everything else, including
whether the rule is enabled and its channel, is kept. Pass an empty value
to clear a setting (--channel-id ""), and --disabled=false to re-enable.
Accepts the same flags as "apps alerts create".

Flags:
--name string display name for the rule (required)
--kind string threshold, crashloop, cert_expiry, cert_expiring, cert_renewal_stalled, patch_status, scheduled_task_failure, node_disk_space, node_resource_usage, domain_health, domain_not_resolving, domain_traffic_drop, parked_domain_cert_expiry, domain_registration_expiry, backup_missing, node_offline, node_cert_expiring, control_plane_backup_stale, log_archive_stale, export_behind, backup_copy_behind, audit_chain_broken, backup_size_anomaly, deploy_duration_regression, or slo_burn (required)
--name string display name for the rule
--kind string threshold, crashloop, cert_expiry, cert_expiring, cert_renewal_stalled, patch_status, scheduled_task_failure, node_disk_space, node_resource_usage, domain_health, domain_not_resolving, domain_traffic_drop, parked_domain_cert_expiry, domain_registration_expiry, backup_missing, node_offline, node_cert_expiring, control_plane_backup_stale, log_archive_stale, export_behind, backup_copy_behind, audit_chain_broken, backup_size_anomaly, deploy_duration_regression, or slo_burn
--metric string metric name (--kind threshold only)
--comparator string >, <, >=, or <= (--kind threshold only)
--threshold float threshold value (--kind threshold only)
--for-duration string how long the condition must hold before firing, e.g. "2m" (--kind threshold or domain_health); overdue grace period (--kind backup_missing, default 6h); max snapshot age (--kind control_plane_backup_stale, default 3d); max time since a successful archive (--kind log_archive_stale, default 3 intervals, at least 2h); max time without a delivery (--kind export_behind, default 15m)
--slo float SLO target percentage of good requests, e.g. 99.9 (--kind slo_burn, required for it)
--slo float SLO target percentage of good requests, e.g. 99.9 (--kind slo_burn)
--slo-latency-ms float make the SLO a latency SLO: good means finishing within this many ms (--kind slo_burn)
--restart-count-threshold int restart count (--kind crashloop) or consecutive-failure count (--kind scheduled_task_failure) that triggers firing
--restart-window string time window restarts are counted in, e.g. "5m" (--kind crashloop only)
Expand All @@ -580,7 +490,7 @@ Flags:
--channel-id string attach an already-connected notification channel
--notify-url string legacy alternative to --channel-id
--notify-kind string legacy alternative to --channel-id
--disabled leave the rule disabled (default: enabled)
--disabled disable the rule, or enable it with --disabled=false
`+alertNoiseFlagsUsage+` --token string API token (default: %[2]s env var, then the credentials file)
--api-url string control plane base URL (default: %[3]s env var, then %[4]s)
--profile string named credentials profile to read (overrides APP_PROFILE, default "default")
Expand Down
41 changes: 28 additions & 13 deletions cmd/levelrail-cli/apps_alerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -289,26 +290,40 @@ func TestRun_AppsAlertsUpdate_Threshold(t *testing.T) {
}
}

func TestRun_AppsAlertsUpdate_MissingKind(t *testing.T) {
var stdout, stderr bytes.Buffer
got := run("levelrail-cli-test", []string{"apps", "alerts", "update", "web", "alr_1", "--name", "x"}, &stdout, &stderr, envMap())
if got != exitValidation {
t.Fatalf("exit = %d, want %d (stderr=%q)", got, exitValidation, stderr.String())
}
if !strings.Contains(stderr.String(), "--kind is required") {
t.Errorf("stderr = %q, want a missing --kind error", stderr.String())
func TestRun_AppsAlertsUpdate_SendsOnlySuppliedFlags(t *testing.T) {
cases := []struct {
args []string
want string
}{
{[]string{"--threshold", "95"}, `{"threshold":95}`},
{[]string{"--threshold", "0", "--channel-id", ""}, `{"channel_id":"","threshold":0}`},
{[]string{"--disabled=false"}, `{"enabled":true}`},
{[]string{"--disabled", "--label", "team=a"}, `{"enabled":false,"labels":{"team":"a"}}`},
{[]string{"--slo", "99.5"}, `{"slo":{"target":99.5}}`},
}
for _, tc := range cases {
var gotQuery, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.RawQuery
raw, _ := io.ReadAll(r.Body)
gotBody = strings.TrimSpace(string(raw))
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(alertRuleResource{ID: "alr_1"})
}))
runCLIExpectOK(t, append([]string{"apps", "alerts", "update", "web", "alr_1", "--api-url", srv.URL}, tc.args...))
srv.Close()
if gotQuery != "keep_unset=true" || gotBody != tc.want {
t.Errorf("%v: query=%q body=%s, want %s", tc.args, gotQuery, gotBody, tc.want)
}
}
}

func TestRun_AppsAlertsUpdate_MissingName(t *testing.T) {
func TestRun_AppsAlertsUpdate_NoFlags(t *testing.T) {
var stdout, stderr bytes.Buffer
got := run("levelrail-cli-test", []string{"apps", "alerts", "update", "web", "alr_1", "--kind", "cert_expiry"}, &stdout, &stderr, envMap())
got := run("levelrail-cli-test", []string{"apps", "alerts", "update", "web", "alr_1"}, &stdout, &stderr, envMap())
if got != exitValidation {
t.Fatalf("exit = %d, want %d (stderr=%q)", got, exitValidation, stderr.String())
}
if !strings.Contains(stderr.String(), "--name is required") {
t.Errorf("stderr = %q, want a missing --name error", stderr.String())
}
}

func TestRun_AppsAlertsUpdate_MissingArgs(t *testing.T) {
Expand Down
116 changes: 116 additions & 0 deletions cmd/levelrail-cli/apps_alerts_update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package main

import (
"context"
"flag"
"fmt"
"io"
"strings"
)

// alertUpdateFields maps a flag to its wire field; flags with a shape of their own are handled separately.
var alertUpdateFields = []string{
"name", "kind", "metric", "comparator", "threshold", "for-duration", "restart-count-threshold",
"restart-window", "scheduled-task-id", "backup-resource-kind", "backup-database-name", "backup-volume-name",
"channel-id", "notify-url", "notify-kind", "severity", "consecutive-failures", "flap-threshold",
"flap-window", "escalate-channel-id", "escalate-after", "runbook",
}

// alertUpdateBody builds the partial body from the supplied flags only, so omitted settings stay as stored.
func alertUpdateBody(fs *flag.FlagSet, appName string, noise *alertNoiseFlags, slo *sloFlags) (map[string]any, error) {
// ref: 9f125bca40ff
set := map[string]*flag.Flag{}
fs.Visit(func(f *flag.Flag) { set[f.Name] = f })
body := map[string]any{}
for _, name := range alertUpdateFields {
f, ok := set[name]
if !ok {
continue
}
getter, ok := f.Value.(flag.Getter)
if !ok {
return nil, fmt.Errorf("flag --%s has no value", name)
}
body[strings.ReplaceAll(name, "-", "_")] = getter.Get()
}
if f, ok := set["disabled"]; ok {
body["enabled"] = f.Value.String() != "true"
}
// A volume belongs to the app in the URL, the same as on create.
if _, ok := set["backup-volume-name"]; ok {
body["backup_service_name"] = appName
}
if _, ok := set["label"]; ok {
labels, err := labelMap(noise.labels)
if err != nil {
return nil, err
}
body["labels"] = labels
}
cfg := map[string]any{}
if _, ok := set["slo"]; ok {
cfg["target"] = slo.target
}
if _, ok := set["slo-latency-ms"]; ok {
full := slo.config()
cfg["objective"], cfg["latency_ms"] = full.Objective, full.LatencyMs
}
if len(cfg) > 0 {
body["slo"] = cfg
}
return body, nil
}

func runAppsAlertsUpdate(prog string, args []string, stdout, stderr io.Writer, lookupEnv func(string) (string, bool)) int {
fs, tokenFlagP, apiURLFlagP, profileFlagP, jsonOutP, outputFlagP, queryFlagP := apiFlagSet(prog, "apps alerts update", "print the updated rule as JSON to stdout and nothing else", stderr)
fs.String("name", "", "display name for the rule")
fs.String("kind", "", "rule kind, see \"apps alerts create\"")
fs.String("metric", "", "metric name (threshold rules)")
fs.String("comparator", "", "one of >, <, >=, <= (threshold rules)")
fs.Float64("threshold", 0, "threshold value")
fs.String("for-duration", "", "how long the condition must hold before firing, e.g. \"2m\"")
fs.Int("restart-count-threshold", 0, "restart or consecutive-failure count that triggers firing")
fs.String("restart-window", "", "time window restarts are counted in, e.g. \"5m\"")
fs.String("scheduled-task-id", "", "which of this app's scheduled tasks to watch")
registerBackupMissingFlags(fs)
fs.String("channel-id", "", "notification channel id, empty to detach (see \"channels list\")")
fs.String("notify-url", "", "legacy alternative to --channel-id: a raw webhook URL/destination")
fs.String("notify-kind", "", "legacy alternative to --channel-id, see \"apps alerts create\"")
fs.Bool("disabled", false, "disable the rule, or enable it with --disabled=false")
noise := registerAlertNoiseFlags(fs)
slo := registerSLOFlags(fs)
fs.Usage = func() { _, _ = fmt.Fprint(stderr, appsAlertsUpdateUsage(prog)) }

tokenFlag, apiURLFlag, profileFlag, jsonOut, of, exitCode, ok := parseAPIFlags(fs, args, apiFlagPtrs{tokenFlagP, apiURLFlagP, profileFlagP, jsonOutP, outputFlagP, queryFlagP}, prog, stderr)
if !ok {
return exitCode
}

rest, argsOK := requireArgs(fs, stderr, prog, "apps alerts update", "an app name and a rule id", 2)
if !argsOK {
return exitUsage
}
appName, id := rest[0], rest[1]

body, err := alertUpdateBody(fs, appName, noise, slo)
if err != nil {
return reportError(stdout, stderr, jsonOut, err)
}
if len(body) == 0 {
return reportError(stdout, stderr, jsonOut, newValidationError("nothing to update: pass at least one setting flag"))
}

client := apiClientFromFlags(prog, apiURLFlag, tokenFlag, profileFlag, lookupEnv)
updated, err := client.PatchAlertRule(context.Background(), appName, id, body)
if err != nil {
return reportError(stdout, stderr, jsonOut, fmt.Errorf("update alert rule %q for app %q: %w", id, appName, err))
}

if err := renderResult(stdout, of.Format, of.Query, updated, func() {
_, _ = fmt.Fprintf(stdout, "alert rule %q (id %s, kind %s) updated for app %q\n", updated.Name, updated.ID, updated.Kind, appName)
}); err != nil {
_, _ = fmt.Fprintln(stderr, err)
return exitCodeForError(err)
}
return exitOK
}
3 changes: 3 additions & 0 deletions cmd/levelrail-cli/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,9 @@ func printDatabaseHuman(out io.Writer, d databaseResource) {
if d.BackupSchedule != "" {
_, _ = fmt.Fprintf(out, "backup: %s (target %s)\n", d.BackupSchedule, d.BackupTargetID)
}
if d.BackupSkipReason != "" {
_, _ = fmt.Fprintf(out, "skipped: %s: %s\n", d.BackupSkippedAt, d.BackupSkipReason)
}
}

// printDatabasesTable prints a compact, aligned table of databases
Expand Down
2 changes: 1 addition & 1 deletion docs/alerts.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Rules belong to an app and live under `apps alerts`:
levelrail-cli apps alerts create web --name "High CPU" --kind threshold --metric cpu_percent --comparator ">" --threshold 90 --for-duration 5m --channel-id CHANNEL_ID --severity warning
levelrail-cli apps alerts create web --name "Restart loop" --kind crashloop --restart-count-threshold 3 --restart-window 5m --channel-id CHANNEL_ID
levelrail-cli apps alerts list web
levelrail-cli apps alerts update web RULE_ID --kind threshold --metric cpu_percent --comparator ">" --threshold 95
levelrail-cli apps alerts update web RULE_ID --threshold 95
levelrail-cli apps alerts delete web RULE_ID
levelrail-cli apps alerts template web --profile-type web --channel CHANNEL_ID
```
Expand Down
Loading
Loading