# Grafana

Connect [Grafana](https://grafana.com/oss/grafana/) to the engine that reads your logs, spans or metrics. Grafana’s SQL data sources provide the dashboard time range and bucket size for time-series panels.

| You have | Grafana data source |
|---|---|
| OpenTelemetry or Prometheus remote-write metrics in a bucket | Built-in [Prometheus](#prometheus), against Send2Bucket's query API |
| Records loaded into PostgreSQL or MySQL | Built-in [PostgreSQL or MySQL](#postgresql) |
| ClickHouse | [ClickHouse](https://grafana.com/grafana/plugins/grafana-clickhouse-datasource/) plugin by Grafana Labs |
| Trino or Starburst | [Trino](https://grafana.com/grafana/plugins/trino-datasource/) community plugin |
| BigQuery | [Google BigQuery](https://grafana.com/grafana/plugins/grafana-bigquery-datasource/) plugin by Grafana Labs |
| Athena | [Amazon Athena](https://grafana.com/grafana/plugins/grafana-athena-datasource/) plugin by Grafana Labs |
| MotherDuck or a DuckDB file | MotherDuck's DuckDB plugin |

## Prometheus

Send2Bucket's query API answers Prometheus's HTTP API under `/v1/query/prom`, so Grafana's built-in Prometheus data source charts metrics straight from a destination's bucket with PromQL. It reads Prometheus remote-write series and OpenTelemetry gauges, sums and histograms; see [Metric names and labels](#metric-names-and-labels).

![A Grafana dashboard of OpenTelemetry host metrics and Prometheus remote-write metrics, read through the Prometheus data source](/img/docs/grafana/dashboard.webp)

You need:

| Field | Value |
|---|---|
| Prometheus server URL | `https://api.send2bucket.com/v1/query/prom` |
| `Authorization` header | `Bearer <query_key>`: a query key from **Query > agents** in the dashboard, which can only query its own organization |
| `X-S2B-Destination` header | The destination's ID, from `GET /v1/manage/destinations` in the [management API](../../management-api.md) |

Add the data source under **Connections > Data sources > Prometheus**, put both headers under **HTTP headers**, and set **HTTP method** to `POST`. Or provision it from a file in `provisioning/datasources/`:

```yaml
apiVersion: 1
datasources:
  - name: Send2Bucket
    uid: s2b-prom
    type: prometheus
    access: proxy
    url: https://api.send2bucket.com/v1/query/prom
    jsonData:
      httpMethod: POST
      prometheusType: Prometheus
      prometheusVersion: 2.53.0
      timeInterval: 15s
      httpHeaderName1: Authorization
      httpHeaderName2: X-S2B-Destination
    secureJsonData:
      httpHeaderValue1: Bearer $S2B_QUERY_KEY
      httpHeaderValue2: <destination_id>
```

**Save & test** runs a test query against the API:

![Grafana's data source test: Successfully queried the Prometheus API](/img/docs/grafana/datasource-test.webp)

Set `timeInterval` to the interval your senders export at, so `$__rate_interval` covers at least two samples. Explore and the query builder list metric names and label values from the dashboard's time range:

![Grafana's metric picker listing system_ metrics from Send2Bucket](/img/docs/grafana/metric-picker.webp)

### Metric names and labels

OpenTelemetry metrics follow OpenTelemetry's Prometheus compatibility rules, without unit suffixes:

| OTLP | Prometheus |
|---|---|
| `system.cpu.time`, a monotonic sum | `system_cpu_time_total` |
| `system.memory.usage`, a gauge | `system_memory_usage` |
| A histogram `http.server.duration` | `http_server_duration_bucket` with `le`, `_sum` and `_count` |
| `service.namespace` and `service.name` | `job`, as `<namespace>/<name>` |
| `service.instance.id` | `instance` |
| Data point attributes | Labels, with characters outside `[a-zA-Z0-9_]` replaced by `_` |

Remote-write series keep the names and labels they were sent with. Example panels:

```promql
sum by (state) (rate(system_cpu_time_total[$__rate_interval]))
histogram_quantile(0.9, sum by (le) (rate(http_server_duration_bucket[$__rate_interval])))
avg_over_time(process_resident_memory_bytes[5m])
```

### What PromQL covers

| Supported | Not yet |
|---|---|
| Selectors with `=`, `!=`, `=~`, `!~` and `offset` | `group_left` and `group_right` |
| `rate`, `irate`, `increase`, `delta`, `idelta`, `*_over_time` | `label_replace` and `label_join` |
| `sum`, `avg`, `min`, `max`, `count`, `stddev`, `stdvar`, `group` with `by` or `without` | `topk`, `bottomk`, `quantile` and `count_values` |
| Arithmetic, comparisons with `bool`, `and`, `or`, `unless`, `on` and `ignoring` | Subqueries |
| `histogram_quantile`, `abs`, `ceil`, `floor`, `round`, `sqrt`, `exp`, `ln`, `log2`, `log10`, `clamp_min`, `clamp_max`, `vector` | Exponential histograms, summaries, exemplars and recording rules |

An unsupported query returns an error naming what is missing.

Each panel query is one query on your plan: it uses the plan's query compute, and queries beyond its concurrency wait for a slot instead of failing. A query reads the hours its time range covers and the metric names it selects, so dashboards over the last hours stay fast; a regex on `__name__` reads every metric in range.

## PostgreSQL

Load records on a schedule as in [PostgreSQL](../../querying/postgres.md). Create a role that can only read, as in [Metabase](./metabase.md#postgresql-or-mysql), then add the data source under **Connections > Data sources > PostgreSQL**, or provision it from a file in `provisioning/datasources/`:

```yaml
apiVersion: 1
datasources:
  - name: Send2Bucket
    uid: s2b-postgres
    type: grafana-postgresql-datasource
    url: <postgres_host>:5432
    user: grafana
    jsonData:
      database: <database>
      sslmode: require
      postgresVersion: 1500
    secureJsonData:
      password: $S2B_PG_PASSWORD
```

Grafana replaces `$S2B_PG_PASSWORD` with the environment variable of that name when it starts, so the password stays out of the file. Older Grafana releases call the type `postgres`.

### Time series panels

`$__timeFilter` limits a query to the dashboard's time range, and `$__timeGroupAlias` buckets rows into a `time` column. Records per signal per minute, one series per signal:

```sql
SELECT $__timeGroupAlias(received_at, '1m', 0),
       signal AS metric,
       count(*) AS records
FROM s2b_records
WHERE $__timeFilter(received_at)
GROUP BY 1, 2
ORDER BY 1
```

Set the query's **Format** to **Time series**. A column named `metric` becomes the series name, and the `0` fills minutes with no records with zero instead of leaving gaps.

`order.paid` revenue per interval, with `$__interval` following the panel's width:

```sql
SELECT $__timeGroupAlias(received_at, $__interval, 0),
       sum((data->>'cents')::numeric) / 100 AS revenue_usd
FROM s2b_records
WHERE $__timeFilter(received_at)
  AND signal = 'event' AND data->>'event' = 'order.paid'
GROUP BY 1
ORDER BY 1
```

p95 span duration per minute:

```sql
SELECT $__timeGroupAlias(received_at, '1m'),
       percentile_cont(0.95) WITHIN GROUP (
         ORDER BY ((data->>'endTimeUnixNano')::numeric
                 - (data->>'startTimeUnixNano')::numeric) / 1e6) AS p95_ms
FROM s2b_records
WHERE $__timeFilter(received_at) AND signal = 'span'
GROUP BY 1
ORDER BY 1
```

`received_at` is when Send2Bucket accepted the record. To plot by when a span started, use `to_timestamp((data->>'startTimeUnixNano')::numeric / 1e9)` as the time column instead. That expression has no index, so keep `$__timeFilter(received_at)` in the `WHERE` clause as well.

### Table panels

Set **Format** to **Table** for breakdowns. Logs by service and severity in the selected range:

```sql
SELECT jsonb_path_query_first(resource,
         '$.attributes[*] ? (@.key == "service.name").value.stringValue') #>> '{}' AS service,
       data->>'severityText' AS severity,
       count(*) AS logs
FROM s2b_records
WHERE $__timeFilter(received_at) AND signal = 'log'
GROUP BY service, severity
ORDER BY logs DESC
```

The other questions come from [PostgreSQL: Example queries](../../querying/postgres.md#example-queries) with `$__timeFilter(received_at)` added.

### MySQL

The MySQL data source has the same macros. Use the `received_at` column of the [MySQL](../../querying/mysql.md) table, which holds UTC times, and set the data source's time zone to UTC.

## ClickHouse, Trino, BigQuery and Athena

Install the plugin from **Administration > Plugins and data > Plugins**, or with `grafana cli plugins install <plugin_id>`, then add the data source with a read-only user or key:

| Data source | Plugin ID | Credentials | SQL |
|---|---|---|---|
| ClickHouse | `grafana-clickhouse-datasource` | User with `SELECT` on the tables | [ClickHouse](../../querying/clickhouse.md) |
| Trino | `trino-datasource` | Trino user, over HTTPS | [Trino](../../querying/trino.md) |
| BigQuery | `grafana-bigquery-datasource` | Service account with BigQuery Data Viewer and Job User | [BigQuery](../../querying/bigquery.md) |
| Athena | `grafana-athena-datasource` | IAM keys or role allowed to run Athena queries and read the prefix | [Athena](../../querying/athena.md) |

Each plugin has its own time macros, such as `$__timeFilter(column)`. Check the plugin's documentation for its exact names. Every panel refresh runs a query, which costs money on BigQuery and Athena: filter on the `date` partition column as well as the time column, and set dashboard refresh intervals of minutes, not seconds.

## DuckDB and MotherDuck

MotherDuck publishes a DuckDB data source plugin (`motherduck-duckdb-datasource`) for local DuckDB files and MotherDuck databases. It is unsigned, so allow it with `GF_PLUGINS_ALLOW_LOADING_UNSIGNED_PLUGINS=motherduck-duckdb-datasource`, and it needs a glibc-based Grafana image. Point it at the views from [MotherDuck](../motherduck.md) or [DuckDB](../../querying/duckdb.md). See [MotherDuck's Grafana guide](https://motherduck.com/docs/integrations/bi-tools/grafana/) for installation.

## Notes

- Grafana runs every panel's query on each dashboard load and refresh. A query over gzip objects in a bucket is slow for that, so chart a loaded table or a table destination.
- For alerting on Send2Bucket data, such as error log counts, use the same queries in Grafana alert rules. The query must return a time series or a single number.
- OTLP timestamps are nanosecond strings. Cast them before arithmetic, as above.
