mariadb_exporter 0.11.0

MariaDB metric exporter for Prometheus
docs.rs failed to build mariadb_exporter-0.11.0
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Visit the last successful build: mariadb_exporter-0.9.0

Test & Build codecov Crates.io License

mariadb_exporter

MariaDB metrics exporter for Prometheus written in Rust.

Features

  • Modular collectors – Enable only what you need; heavy/optional collectors stay off by default.
  • Compatibility – Metric names align with Prometheus mysqld_exporter (prefixed mariadb_).
  • Lean defaults – Essential availability, InnoDB, and replication metrics enabled by default; optional collectors opt-in.
  • Low footprint – Designed to minimize cardinality and avoid expensive scans.
  • Resilient – Serves /metrics (HTTP 200) even when MariaDB is unreachable. During an outage, mariadb_up becomes 0, and DB-dependent metrics are omitted to avoid stale data. Only an overload of the exporter itself is signalled with a status code — see Scrape concurrency and timeout.
  • No stale data – A collector never serves a previous scrape's values as current. If its source becomes unavailable (plugin uninstalled, performance_schema table missing, feature disabled, privilege revoked) the series it owned disappear instead of freezing. See Scrape outcomes.
  • Optional tracing – OpenTelemetry/OTLP is a default-off Cargo feature. Release binaries keep local logs and x-request-id; rebuild with --features telemetry for OTLP. See Optional OpenTelemetry tracing.

Download or build

Install via Cargo:

cargo install mariadb_exporter

Or grab a prebuilt binary, .deb, or .rpm from the GitHub Releases — built for Linux (x86_64 and aarch64, static musl) and macOS (x86_64 and aarch64). Container images (linux/amd64, linux/arm64) are published to ghcr.io.

Usage

Recommended Setup (Secure)

Best practice: Use Unix socket with dedicated user

Create the exporter user with minimal privileges:

-- Create user for local socket connection only with connection limit
CREATE USER 'exporter'@'localhost' IDENTIFIED BY '' WITH MAX_USER_CONNECTIONS 3;

-- Grant minimal required permissions for all collectors
GRANT SELECT, PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'localhost';

FLUSH PRIVILEGES;

Run the exporter:

mariadb_exporter --dsn "mysql:///mysql?socket=/var/run/mysqld/mysqld.sock&user=exporter"

Why this is secure:

  • ✅ No password needed (socket authentication)
  • ✅ User restricted to localhost only (no network access)
  • ✅ Minimal privileges (read-only + monitoring)
  • ✅ Connection limit prevents resource exhaustion
  • ✅ No exposure to network attacks

Alternative: TCP Connection

For remote monitoring or testing:

mariadb_exporter --dsn "mysql://exporter:password@host:3306/mysql"

Create user for network access:

CREATE USER 'exporter'@'%' IDENTIFIED BY 'strong_password_here' WITH MAX_USER_CONNECTIONS 3;
GRANT SELECT, PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'%';
FLUSH PRIVILEGES;

Common DSN Formats

  • Unix socket (recommended): mysql:///mysql?socket=/var/run/mysqld/mysqld.sock&user=exporter
  • TCP: mysql://user:password@host:3306/database
  • TLS required: mysql://user:password@host/mysql?ssl-mode=REQUIRED
  • TLS verify identity: mysql://user:password@host/mysql?ssl-mode=VERIFY_IDENTITY&ssl-ca=/path/to/ca.pem

Change Port

Default port is 9306:

mariadb_exporter --dsn "..." --port 9187

Available collectors

Collectors are toggled with --collector.<name> or --no-collector.<name>.

  • --collector.default (enabled) – Core status (uptime, threads, connections, traffic), InnoDB basics, replication basics, binlog stats, config flags, version, mariadb_up, audit log enabled status.
  • --collector.exporter (enabled) – Exporter self-metrics (process, scrape, cardinality).
  • --collector.innodb – Advanced InnoDB metrics from SHOW ENGINE INNODB STATUS: LSN tracking, checkpoint age, active transactions, semaphore waits, adaptive hash index stats.
  • --collector.tls – TLS session + cipher info.
  • --collector.query_response_time – Buckets from query_response_time plugin.
  • --collector.statements – Statement digest summaries/top latency from performance_schema.
  • --collector.schema – Table size/row estimates (largest 20 non-system tables).
  • --collector.replication – Replica role/lag/thread status, relay log size/pos, binlog file count, and per-channel replication metrics for multi-source replicas.
  • --collector.locks – Metadata/table lock waits from performance_schema.
  • --collector.metadata – metadata_lock_info table counts.
  • --collector.userstat – Per-user stats (requires @@userstat=1 and USER_STATISTICS).
  • --collector.system – Host CPU/memory/load and MariaDB process-group usage, read from the OS (never from the database). Only meaningful when the exporter runs on the database host. See src/collectors/system/README.md. Process-group memory is read from /proc/<pid>/statm (RSS); --system.process-memory=pss switches to /proc/<pid>/smaps_rollup, which accounts shared pages proportionally but makes the kernel walk every page-table entry — budget for it before enabling.

Enabled by default

  • default
  • exporter

Everything else is opt-in.

Replication lag semantics:

  • mariadb_slave_status_seconds_behind_master and mariadb_replica_seconds_behind_master_seconds use -1 for unknown lag (NULL, stopped replication, query failure, or not a replica).
  • On multi-source replicas, aggregate lag is the worst known channel lag (max), and aggregate *_io_running / *_sql_running are 1 only when all channels are running.
  • Per-channel replication metrics are exported as mariadb_replica_*_by_channel{channel_name,connection_name}.

Enable all collectors

To enable all collectors for maximum visibility:

mariadb_exporter \
  --dsn "mysql:///mysql?socket=/var/run/mysqld/mysqld.sock&user=exporter" \
  --collector.default \
  --collector.exporter \
  --collector.innodb \
  --collector.tls \
  --collector.query_response_time \
  --collector.statements \
  --collector.schema \
  --collector.replication \
  --collector.locks \
  --collector.metadata \
  --collector.userstat \
  --collector.system

Or using environment variables:

export MARIADB_EXPORTER_DSN="mysql:///mysql?socket=/var/run/mysqld/mysqld.sock&user=exporter"
export MARIADB_EXPORTER_PORT="9306"

mariadb_exporter \
  --collector.default \
  --collector.exporter \
  --collector.innodb \
  --collector.tls \
  --collector.query_response_time \
  --collector.statements \
  --collector.schema \
  --collector.replication \
  --collector.locks \
  --collector.metadata \
  --collector.userstat \
  --collector.system

Note: Some collectors require additional privileges or database configuration:

  • innodb – Requires PROCESS privilege (included in recommended setup)
  • tls – Only shows data if TLS/SSL is enabled
  • query_response_time – Requires query_response_time plugin enabled
  • statements – Requires performance_schema enabled
  • schema – Queries information_schema (can be slow on large databases)
  • locks, metadata – Require performance_schema enabled
  • userstat – Requires @@userstat=1 and USER_STATISTICS enabled
  • system – Reads the OS, not the database. Only enable it when the exporter runs on the same host as MariaDB; on managed services (RDS, SkySQL, …) it would describe the exporter's host instead

InnoDB Advanced Metrics

The --collector.innodb provides deep visibility into InnoDB internals by parsing SHOW ENGINE INNODB STATUS:

Metrics exposed:

  • mariadb_innodb_lsn_current – Current log sequence number
  • mariadb_innodb_lsn_flushed – LSN flushed to disk
  • mariadb_innodb_lsn_checkpoint – Last checkpoint LSN
  • mariadb_innodb_checkpoint_age_bytes – Uncheckpointed bytes (LSN current - checkpoint)
  • mariadb_innodb_active_transactions – Count of active InnoDB transactions
  • mariadb_innodb_semaphore_waits_total – Semaphore wait events (internal contention)
  • mariadb_innodb_semaphore_wait_time_ms_total – Total semaphore wait time
  • mariadb_innodb_adaptive_hash_searches_total – Adaptive hash index hits
  • mariadb_innodb_adaptive_hash_searches_btree_total – AHI misses requiring B-tree lookup

Use cases:

  • Monitor checkpoint age to prevent log file overflow
  • Track LSN progression for write workload analysis
  • Detect long-running transactions
  • Identify internal InnoDB contention (semaphore waits)
  • Measure adaptive hash index efficiency

Requirements:

  • PROCESS privilege (for SHOW ENGINE INNODB STATUS)

Enable with:

mariadb_exporter --collector.default --collector.innodb

Scrape outcomes

Every collector reports one of three outcomes per scrape, and the exporter settles the registry accordingly.

Outcome Meaning Effect on the registry /metrics
Fresh The collector published a current snapshot. A successful empty result is Fresh when "zero rows" is the current truth. The new snapshot replaces the old one; entities that vanished from a valid snapshot are removed. Exposed as usual.
Skipped The collector published nothing because its source is known to be unavailable — plugin not installed, performance_schema table absent, feature disabled, privilege revoked. Every series the collector owned is removed. Those series are absent. Siblings are unaffected.
Err An unexpected or transient fault — lost connection, timeout, deadlock, malformed data, or a feature probe that itself failed. The last good snapshot is preserved so the collector can resume. HTTP 200 with mariadb_up 1, # Error collecting metrics from '<name>': … comments, and only the mariadb_exporter_* self-observation families. Database-dependent families are withheld for that scrape so a preserved snapshot is never timestamped as current.

Connectivity failure is unchanged: HTTP 200, mariadb_up 0, fresh exporter/build metrics, and no database metrics. mariadb_up is never fabricated to 0 because a collector failed — the connectivity check succeeded, so it stays 1.

Scrape concurrency and timeout

The three outcomes above describe a scrape that ran. Two situations are about the scrape itself and are answered with a status code instead, because there is no honest exposition to return:

Situation Status Meaning
A scrape is already in flight 503 Service Unavailable /metrics is single-flight. Overlapping scrapes are refused rather than piled onto an already-slow server.
The scrape exceeded --scrape.timeout-ms 504 Gateway Timeout The scrape was aborted, so its in-flight queries were dropped and their pooled connections returned.

--scrape.timeout-ms defaults to 15000. Set it below your Prometheus scrape_timeout so the exporter, not the scraper, decides when to give up.

Note that the shipped default does not satisfy that advice: Prometheus's own scrape_timeout defaults to 10s, which is below 15000ms, so with both defaults the scraper gives up first and the exporter's budget never fires. Nothing breaks — the client disconnect drops the request future, which releases the gate and aborts the scrape — but the 504 never appears and the decision of when to give up stays with Prometheus. Lower --scrape.timeout-ms below your scrape_timeout to move it back to the exporter.

The single-flight gate is held by the request, not by the scrape task. It is therefore released on every exit path — success, collector error, panic, timeout, and client disconnect — so a scrape that never finishes cannot wedge /metrics at 503 permanently (nbari/pg_exporter#34).

A gate release is not a promise that all work has finished: a spawn_blocking sample already running cannot be cancelled, and the server may still be finishing a statement it was told to stop. The gate bounds exporter concurrency, not server-side work; a role-level connection limit is the hard backstop there.

An aborted scrape is recorded as an abort, never as a success: every collector still in flight increments mariadb_exporter_collector_scrape_aborted_total{collector="..."} and reports mariadb_exporter_collector_last_scrape_success 0. Alert on rate(mariadb_exporter_collector_scrape_aborted_total[5m]) > 0 to catch a collector that is not finishing within --scrape.timeout-ms — the collector is not necessarily at fault, since the abort bounds the whole scrape.

Per-collector timers only start after the connectivity check, so a scrape abandoned while SELECT 1 is still in flight moves none of them. mariadb_exporter_scrape_aborted_total counts that case: it is incremented once per scrape, without a collector label, whenever a scrape exceeds --scrape.timeout-ms.

The two counters are deliberately asymmetric, because a client disconnect and a budget timeout are not observed the same way. A disconnect drops the request future, so no code in the exporter runs at that point — it cannot increment a scrape-level counter. Those aborts are visible only through the per-collector counter, and only for collectors that had already started. A budget timeout, by contrast, is observed by the exporter itself and increments both.

Alerting implications

Because an unavailable source now yields absence rather than a stale or zero value, threshold alerts on those series go quiet instead of firing on stale data. Alerts that need to notice a disappearing source should use absent() / absent_over_time(), and scrape health should be watched with the exporter's own metrics:

# The exporter is up but a collector keeps failing.
mariadb_exporter_collector_last_scrape_success == 0

# A source that used to report has gone away.
absent_over_time(mariadb_info_schema_query_response_time_seconds_count[10m])

An honest zero is still published where zero is a fact — for example mariadb_ssl_server_configured 0 when TLS is genuinely not in use, or mariadb_replica_configured 0 on a server with no replication. A zero is never published to stand in for "could not read".

On normal shutdown (SIGINT or SIGTERM on Unix), the exporter drains its HTTP server, then waits up to two seconds for the shared MariaDB pool to close gracefully, including TLS shutdown. Exceeding that pool-close limit returns an error and a nonzero exit status.

Project layout

mariadb_exporter
├── bin
├── cli
├── collectors
│   ├── config.rs
│   ├── default
│   ├── exporter
│   ├── innodb
│   ├── locks
│   ├── metadata
│   ├── mod.rs
│   ├── query_response_time
│   ├── register_macro.rs
│   ├── registry.rs
│   ├── replication
│   ├── schema
│   ├── statements
│   ├── system
│   ├── tls
│   ├── userstat
│   └── util.rs
└── src/lib.rs

Each collector lives in its own subdirectory for clarity and easy extension.

Optional OpenTelemetry tracing

OpenTelemetry/OTLP support is a default-off Cargo feature. Standard release binaries, packages, and container images omit it. Prometheus metrics, local logs (RUST_LOG / -v), request spans, and x-request-id correlation remain available in every build.

Build Endpoint configured Behavior
Default No Local logging only
Default Yes Local logging only; startup warning that OTEL configuration is ignored
--features telemetry No Local logging only; no exporter is started
--features telemetry Yes Local logging plus OTLP/gRPC traces, incoming trace context, and x-trace-id responses for active traces
cargo build --release --features telemetry
./target/release/mariadb_exporter --version  # reports telemetry: enabled
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
  ./target/release/mariadb_exporter -v

Only OTLP/gRPC is supported. Optional OTEL_EXPORTER_OTLP_HEADERS supplies comma-separated key=value authentication metadata; HTTPS uses native certificate roots. A default build warns once on stderr when OTEL_EXPORTER_OTLP_ENDPOINT is set and never prints the endpoint or header values.

For a custom telemetry-enabled image:

podman build -f Containerfile --build-arg CARGO_FEATURES=telemetry -t mariadb-exporter:telemetry .

Testing

Zero-setup option: the repo ships a compose-based Dev Container (Rust + MariaDB, plus an optional Prometheus + Grafana profile). With DevPod: scripts/dev-up, then just test inside — no host database needed.

Run tests:

cargo test

Run with container-backed integration (requires a container runtime):

just test

If you use rootless Podman, export DOCKER_HOST so testcontainers can connect:

export DOCKER_HOST="unix:///run/user/$UID/podman/podman.sock"

Test with Unix socket connection (production-like setup):

# Test with combined MariaDB + exporter container (most realistic)
just test-socket

Lint both the default build and the telemetry feature:

cargo clippy --all-targets
cargo clippy --all-targets --all-features

Socket Connection Testing

For detailed information on testing with Unix socket connections, see TESTING_SOCKET.md.

Quick start:

# Test with combined MariaDB + exporter container (most realistic)
just test-socket

Developer Guidelines

See the Development Guide (CONTRIBUTING.md) for the full local workflow, safe-coding rules, and the pre-commit hook. Additional tooling:

  • .devcontainer/ — one-command Rust + MariaDB dev environment (+ optional Prometheus/Grafana via just metrics-dev).
  • scripts/benchmark/ — self-contained local soak/leak harness (run-soak.sh + check-soak.sh) driven by mariadb_loadtest.py.

Architecture

The project follows a modular collector architecture:

mariadb_exporter/
├── bin/                 # Binary entry point
├── cli/                 # CLI argument parsing
├── collectors/          # All metric collectors
│   ├── mod.rs          # Collector trait and registration
│   ├── registry.rs     # Collector orchestration
│   ├── config.rs       # Collector enable/disable logic
│   └── */              # Individual collector modules
└── exporter/           # HTTP server (Axum)

Adding a New Collector

  1. Create a subdirectory under src/collectors/ with a mod.rs
  2. Define a struct implementing the Collector trait:
    • register_metrics(&self, registry: &Registry) - Register Prometheus metrics
    • collect(&self, pool: &MySqlPool) - Fetch data and update metrics (async)
    • enabled_by_default(&self) - Whether collector runs by default
  3. Add ONE line to register_collectors! macro in src/collectors/mod.rs:
    register_collectors! {
        // ... existing collectors ...
        your_collector => YourCollector,
    }
    

The macro automatically generates all registration boilerplate.

Strict Linting Rules

This project enforces strict clippy lints (see Cargo.toml):

  • DENY: unwrap_used, expect_used, panic, indexing_slicing, await_holding_lock
  • Use ? for error propagation, never .unwrap() or .expect()
  • Use .get() instead of [index] for slicing
  • Use pattern matching or .ok() instead of .unwrap()

Exceptions are allowed only in test code with #[allow(clippy::unwrap_used)].

Testing

# Run unit tests
cargo test

# Run with container integration
just test

# Lint (must pass)
cargo clippy --all-targets --all-features

# Validate Grafana dashboard
just validate-dashboard

Dashboard Development

When adding metrics to the Grafana dashboard:

  1. Ensure metrics are exported by collectors
  2. Add panels following existing structure (clean, professional, no emojis)
  3. Use template variables ($job, $instance)
  4. Add clear descriptions (Goal/Action format)
  5. Validate before committing: just validate-dashboard

See grafana/README.md for detailed dashboard documentation.

Commit Guidelines

  • Run tests before committing: cargo test
  • Run clippy: cargo clippy --all-targets --all-features
  • Validate dashboard if modified: just validate-dashboard
  • Keep commit messages clear and descriptive

Notes

  • User statistics: enable with SET GLOBAL userstat=ON; (or @@userstat=1) to expose userstat metrics.
  • Metadata locks: load metadata_lock_info plugin for the metadata collector.
  • Performance schema is needed for statements/locks collectors to return data.
  • Optional collectors skip gracefully when prerequisites aren't present.