Skip to content
Open
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ Access the UI at http://localhost:8000. Log in with the default credentials `adm

Source builds of this fork include a [community PromQL query API](docs/promql.md) for OTLP metrics, with instant and range queries and no Enterprise dependency. See the guide for the supported language subset and limits.

To send firing and recovery events to an automation, see [Generic alert webhook payloads](docs/webhook-alerts.md).

For production deployments, refer to the [installation guide ↗︎](https://www.parseable.com/docs/self-hosted/installation) for best practices and hardening tips.

> [!TIP]
Expand Down
41 changes: 41 additions & 0 deletions docs/webhook-alerts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generic alert webhook payloads

Generic webhook targets send the existing plain-text message by default. To receive JSON, set `payloadFormat` to `"json"` when creating a target with `POST /api/v1/targets`. For example, the following target uses a placeholder Bearer token.

```json
{
"name": "checkout-automation",
"type": "webhook",
"endpoint": "https://automation.example/hook",
"payloadFormat": "json",
"headers": {"Authorization": "Bearer REPLACE_ME"}
}
```

Upgrade the servers that save targets and deliver alerts before enabling JSON. The earlier fork build at `63f9a416` sends the text body.

In the dashboard target editor, choose **Webhook**, select **JSON** under **Payload format**, and enter the Bearer header under **Custom headers**. Older header-only forms can submit `X-Parseable-Payload-Format` with value `json`. Parseable consumes that instruction on save. The target API returns the selection in `payloadFormat` and masks the endpoint and outbound header values. Authorization requires a destination that matches the tenant's outbound allowlist.

To edit a target, use the dashboard form or send its full specification to `PUT /api/v1/targets/{id}`. Supply the actual endpoint and desired outbound header values when replacing a target. Omitting the format keeps the current selection. Set the format to `text` to switch back. Both API and form inputs accept `text` and `json`. If both are supplied, they must agree.

JSON delivery sets `Content-Type: application/json` even when a different content type was configured. In text mode, an explicitly configured content type is sent alongside the original text bytes.

## Events

A grouped SQL alert can report several services in one notification. For example, an alert with a string-valued custom field `service` and a query grouped by `service.name` could produce this recovery event.

```json
{
"status": "resolved",
"alertId": "01J00000000000000000000000",
"alertName": "Checkout errors",
"severity": "High",
"service": "storefront",
"series": [{"service.name": "checkout"}],
"message": "Checkout errors is now `not-triggered` "
}
```

PromQL delivers one event per series transition. The `series` array contains the original labels for that instance, including on recovery while other instances are still firing. Outbox retries carry the status of the queued transition.

For SQL, a firing event has status `firing`, the evaluator's readable message, and the group labels that breached the threshold. A recovery event has status `resolved` and carries the labels from the most recent firing evaluation. Recovery applies to the whole alert. Use `alertId` to correlate events across evaluations. Ungrouped alerts and alerts recovering from a firing recorded before this feature have an empty `series` array. The optional alert field `service` appears as `null` when unspecified.
3 changes: 3 additions & 0 deletions frontend/e2e/alerts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,8 @@ test('target CRUD masks secrets, requires endpoint re-entry and keeps 409 in the
await status.evaluate((element) => element.setAttribute('data-live-region', 'existing'));
await page.getByRole('button', { name: 'New target', exact: true }).click();
let sheet = page.getByRole('dialog', { name: 'New target', exact: true });
await expect(sheet.getByLabel('Payload format')).toHaveValue('text');
await sheet.getByLabel('Payload format').selectOption('json');
await sheet.getByLabel('Target name').fill('Test hook');
await sheet.getByLabel('Endpoint URL').fill('https://example.com/secret-token');
await sheet.getByRole('button', { name: 'Add header' }).click();
Expand All @@ -504,6 +506,7 @@ test('target CRUD masks secrets, requires endpoint re-entry and keeps 409 in the
await rowAction(page, 'Test hook', 'Edit');
sheet = page.getByRole('dialog', { name: 'Edit target', exact: true });
await expect(sheet.getByLabel('Endpoint URL')).toHaveValue('');
await expect(sheet.getByLabel('Payload format')).toHaveValue('json');
await expect(sheet.getByLabel('Header 1 value')).toHaveValue('');
await expect(sheet.getByLabel('Target name')).toHaveAttribute('readonly', '');
await expect(
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/features/alerts/TargetSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,19 @@ export function TargetSheet({
}
onChange={(event) => update('endpoint', event.target.value)}
/>
{draft.type === 'webhook' && (
<Select
label="Payload format"
value={draft.payloadFormat}
disabled={mutation.pending}
onChange={(event) =>
update('payloadFormat', event.target.value as TargetDraft['payloadFormat'])
}
>
<option value="text">Plain text</option>
<option value="json">JSON</option>
</Select>
)}
{draft.type === 'webhook' && (
<fieldset
className="alerts-fieldset"
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/features/alerts/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,19 @@ describe('target forms', () => {
password: 'Enter the real password, not the mask.',
});
});
it('defaults webhooks to text and preserves an edited JSON selection', () => {
expect(targetDraft().payloadFormat).toBe('text');
const form = targetDraft({
id: 't',
name: 'automation',
type: 'webhook',
endpoint: '',
payloadFormat: 'json',
});
expect(buildTargetPayload(form)).toHaveProperty('payloadFormat', 'json');
form.payloadFormat = 'text';
expect(buildTargetPayload(form)).toHaveProperty('payloadFormat', 'text');
});
it('omits TLS and auth fields for Slack', () => {
const form = {
...targetDraft(),
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/features/alerts/targetHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type TargetDraft = {
name: string;
type: AlertTargetType;
endpoint: string;
payloadFormat: 'text' | 'json';
skipTls: boolean;
username: string;
password: string;
Expand All @@ -27,6 +28,7 @@ export function targetDraft(target?: AlertTarget): TargetDraft {
name: target?.name ?? '',
type: target ? targetType(target) : 'webhook',
endpoint: '',
payloadFormat: target?.payloadFormat ?? 'text',
skipTls: target?.skipTlsCheck ?? false,
// Credentials come back masked, so both start empty and must be re-entered together.
username: '',
Expand Down Expand Up @@ -120,6 +122,7 @@ export function buildTargetPayload(draft: TargetDraft): AlertTargetRequest {
return {
...base,
type: 'webhook',
payloadFormat: draft.payloadFormat,
skipTlsCheck: draft.skipTls,
headers: Object.fromEntries(
draft.headers
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lib/alertsContract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ describe('alerts response contracts', () => {
expect(alertTargetStatus(targetFixture)).toBe(false);
expect(alertTargetStatus({ target: targetFixture, enabled: 'true' })).toBe(false);
expect(alertTarget({ ...targetFixture, headers: { token: 123 } })).toBe(false);
expect(alertTarget({ ...targetFixture, payloadFormat: 'json' })).toBe(true);
expect(alertTarget({ ...targetFixture, payloadFormat: 'xml' })).toBe(false);
expect(alertTarget({ ...targetFixture, skipTlsCheck: 'true' })).toBe(false);
});
});
1 change: 1 addition & 0 deletions frontend/src/lib/alertsContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export function alertTarget(value: unknown): value is AlertTarget {
object(value) &&
['id', 'name', 'endpoint'].every((key) => typeof value[key] === 'string') &&
oneOf(value.type, ['slack', 'webhook', 'alertManager']) &&
(value.payloadFormat === undefined || oneOf(value.payloadFormat, ['text', 'json'])) &&
(value.headers === undefined || labels(value.headers)) &&
(value.skipTlsCheck === undefined || typeof value.skipTlsCheck === 'boolean') &&
(value.username === undefined || nullableString(value.username)) &&
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/lib/demoAlerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export function createDemoAlerts(now = Date.now()): Pick<ParseableClient, Method
if ((sql.match(/\bselect\b/gi) ?? []).length > 1) fail('Subquery not allowed');
}
}
function mask(body: AlertTargetRequest, id: string): AlertTarget {
function mask(body: AlertTargetRequest, id: string, previous?: AlertTarget): AlertTarget {
const endpoint = `${new URL(body.endpoint).protocol}//********`;
if (body.type === 'slack') return { id, name: body.name, type: 'slack', endpoint };
if (body.type === 'alertManager')
Expand All @@ -198,6 +198,7 @@ export function createDemoAlerts(now = Date.now()): Pick<ParseableClient, Method
name: body.name,
type: 'webhook',
endpoint,
payloadFormat: body.payloadFormat ?? previous?.payloadFormat ?? 'text',
headers: Object.fromEntries(Object.keys(body.headers ?? {}).map((key) => [key, '********'])),
skipTlsCheck: body.skipTlsCheck,
};
Expand Down Expand Up @@ -359,7 +360,7 @@ export function createDemoAlerts(now = Date.now()): Pick<ParseableClient, Method
const previous = getTarget(id);
if (body.name !== previous.target.name) fail("Can't modify target name");
validateTargetBody(body);
previous.target = mask(body, id);
previous.target = mask(body, id, previous.target);
previous.enabled = true;
delete previous.error;
return clone(previous.target);
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ export type AlertTargetRequest =
name: string;
type: 'webhook';
endpoint: string;
payloadFormat?: 'text' | 'json';
headers?: Record<string, string>;
skipTlsCheck: boolean;
}
Expand All @@ -352,6 +353,7 @@ export type AlertTarget = {
name: string;
type: AlertTargetType;
endpoint: string;
payloadFormat?: 'text' | 'json';
headers?: Record<string, string>;
skipTlsCheck?: boolean;
username?: string | null;
Expand Down
38 changes: 33 additions & 5 deletions scripts/test-promql-alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ def fail(message):


def request(path, *, method="GET", params=None, body=None, auth=True, timeout=15,
username=None, password=None):
username=None, password=None, stream=None):
url = f"{BASE_URL}{path}"
headers = {"Accept": "application/json"}
if stream is not None:
headers["X-P-Stream"] = stream
if auth:
credentials = (
f"{username if username is not None else USERNAME}:"
Expand Down Expand Up @@ -112,6 +114,18 @@ def ingest(stream, metric, suffix, values):
except urllib.error.HTTPError as exc:
fail(f"OTLP ingestion failed, HTTP {exc.code}: {exc.read().decode(errors='replace')}")

# The scan can end at the minute boundary preceding this successful write.
# Evaluate transitions only after the instant query sees this batch.
deadline = time.monotonic() + max(75, WAIT_SECONDS)
while time.monotonic() < deadline:
status, raw = request("/prometheus/api/v1/query", params={"query": metric}, stream=stream)
vector = data_success(status, raw, "read fixture samples")["result"]
observed = {row["metric"]["host"]: float(row["value"][1]) for row in vector}
if observed == values:
return
time.sleep(1)
fail(f"fixture samples for {stream} did not become queryable")


class LocalWebhook:
"""Tiny loopback receiver that records request bodies for opt-in checks."""
Expand All @@ -122,6 +136,7 @@ def __init__(self):
self.sock.bind(("127.0.0.1", 0))
self.sock.listen()
self.port = self.sock.getsockname()[1]
self.headers = []
self.messages = []
self.statuses = []
self.fail_next = 0
Expand Down Expand Up @@ -151,6 +166,9 @@ def _serve(self):
length = int(line.split(b":", 1)[1].strip())
while len(body) < length:
body += client.recv(4096)
headers = {name.lower(): value.strip() for name, value in
(line.split(b":", 1) for line in head.split(b"\r\n")[1:])}
self.headers.append((headers.get(b"content-type"), headers.get(b"authorization")))
self.messages.append(body[:length].decode(errors="replace"))
status = 503 if self.fail_next else 204
if self.fail_next:
Expand Down Expand Up @@ -257,6 +275,8 @@ def main():
target = {
"name": f"PromQL alert smoke {suffix}",
"type": "webhook",
"payloadFormat": "json",
"headers": {"Authorization": "Bearer local-fixture"},
"endpoint": f"http://127.0.0.1:{receiver.port}/notify",
}
status, raw = request(f"{API_PREFIX}/targets", method="POST", body=target)
Expand All @@ -277,7 +297,8 @@ def main():
"alertType": "threshold",
"thresholdConfig": {"operator": ">", "value": 5},
"promqlConfig": {"holdDuration": "2s"},
"evalConfig": {"rollingWindow": {"evalStart": "1m", "evalEnd": "now", "evalFrequency": 1}},
# This fixture drives each evaluation explicitly, including retry.
"evalConfig": {"rollingWindow": {"evalStart": "1m", "evalEnd": "now", "evalFrequency": 10}},
"notificationConfig": {"interval": 1},
"targets": targets,
}
Expand Down Expand Up @@ -334,7 +355,8 @@ def main():
# Host A fires only after a continuous breach; B starts its own clock later.
ingest(stream, metric, suffix, {"host-a": 9.0, "host-b": 3.0})
evaluate(alert_id)
wait_runtime(alert_id, lambda r: instance(r, "host-a") is not None, "host-a pending")
wait_runtime(alert_id, lambda r: instance(r, "host-a") is not None
and instance(r, "host-a").get("state") == "pending", "host-a pending")
time.sleep(2.1)
evaluate(alert_id)
runtime = wait_runtime(
Expand Down Expand Up @@ -380,8 +402,14 @@ def main():
deadline = time.monotonic() + WAIT_SECONDS
while time.monotonic() < deadline and len(receiver.messages) < 3:
time.sleep(0.1)
if not any("resolved" in message.lower() for message in receiver.messages):
fail(f"local webhook did not receive a recovery notification: {receiver.messages}")
events = [json.loads(message) for message in receiver.messages]
for transition in ("firing", "resolved"):
if not any(event["status"] == transition and event["alertId"] == alert_id
and event["message"] and event["series"][0]["host"] == "host-a"
for event in events):
fail(f"missing {transition} JSON event for host-a")
if any(pair != (b"application/json", b"Bearer local-fixture") for pair in receiver.headers):
fail("incorrect JSON content type or fixture bearer header")

# Create a second rule through a scoped writer so its scheduled identity
# is that user, not the administrator running this smoke test.
Expand Down
17 changes: 17 additions & 0 deletions src/alerts/alert_structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ const RESERVED_FIELDS: &[&str] = &[
"notification_config",
"created",
"tags",
"lastBreachedSeries",
"last_breached_series",
"lastTriggeredAt",
"last_triggered_at",
];
Expand All @@ -88,10 +90,20 @@ pub struct Alerts {
pub sender: mpsc::Sender<AlertTask>,
}

pub type SeriesLabels = HashMap<String, String>;

#[derive(Debug, Clone, Default)]
pub struct AlertNotification {
pub message: String,
pub series: Vec<SeriesLabels>,
}

#[derive(Debug, Clone)]
pub struct Context {
pub alert_info: AlertInfo,
pub deployment_info: DeploymentInfo,
pub service: Option<String>,
pub series: Vec<SeriesLabels>,
pub message: String,
pub notification_config: NotificationConfig,
}
Expand All @@ -106,6 +118,8 @@ impl Context {
Self {
alert_info,
deployment_info,
service: None,
series: Vec::new(),
message,
notification_config,
}
Expand Down Expand Up @@ -403,6 +417,7 @@ impl AlertRequest {
notification_config: self.notification_config,
created: created_timestamp,
tags: self.tags,
last_breached_series: Vec::new(),
last_triggered_at: None,
other_fields,
tenant_id,
Expand Down Expand Up @@ -435,6 +450,8 @@ pub struct AlertConfig {
pub notification_config: NotificationConfig,
pub created: DateTime<Utc>,
pub tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub last_breached_series: Vec<SeriesLabels>,
pub last_triggered_at: Option<DateTime<Utc>>,
#[serde(flatten)]
pub other_fields: Option<serde_json::Map<String, Value>>,
Expand Down
9 changes: 5 additions & 4 deletions src/alerts/alert_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

use crate::{
alerts::{
AlertConfig, AlertError, AlertQueryType, AlertState, AlertType, EvalConfig, Severity,
AlertConfig, AlertError, AlertNotification, AlertQueryType, AlertState, AlertType,
EvalConfig, Severity,
alert_enums::NotificationState,
alert_structs::{Context, ThresholdConfig},
},
Expand Down Expand Up @@ -49,7 +50,7 @@ pub trait MessageCreation {

#[async_trait]
pub trait AlertTrait: Debug + Send + Sync + MetastoreObject {
async fn eval_alert(&self) -> Result<Option<String>, AlertError>;
async fn eval_alert(&self) -> Result<Option<AlertNotification>, AlertError>;
async fn validate(&self, session_key: &SessionKey) -> Result<(), AlertError>;
async fn update_notification_state(
&mut self,
Expand All @@ -58,7 +59,7 @@ pub trait AlertTrait: Debug + Send + Sync + MetastoreObject {
async fn update_state(
&mut self,
alert_state: AlertState,
trigger_notif: Option<String>,
trigger_notif: Option<AlertNotification>,
) -> Result<(), AlertError>;
fn get_id(&self) -> &Ulid;
fn get_severity(&self) -> &Severity;
Expand Down Expand Up @@ -98,7 +99,7 @@ pub trait AlertManagerTrait: Send + Sync {
&self,
alert_id: Ulid,
new_state: AlertState,
trigger_notif: Option<String>,
trigger_notif: Option<AlertNotification>,
tenant_id: &Option<String>,
) -> Result<(), AlertError>;
async fn update_notification_state(
Expand Down
Loading
Loading