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
56 changes: 39 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,3 @@
<!--
Каждый большой README должен начинаться со значков статуса.
Они дают мгновенное представление о состоянии проекта.
Раскомментируй и используй их, когда настроишь соответствующие сервисы.
-->
<!--
[![Статус CI](https://github.com/kvisidisi/pg-bash-exporter/actions/workflows/ci.yml/badge.svg)](https://github.com/kvisidisi/pg-bash-exporter/actions/workflows/ci.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/kvisidisi/pg-bash-exporter)](https://goreportcard.com/report/github.com/kvisidisi/pg-bash-exporter)
[![Лицензия](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
-->

<!--
Название проекта. Должно быть самым крупным элементом (H1).
-->
# PG-Bash Exporter

PG-Bash Exporter — это конфигурируемый экспортер для Prometheus, написанный на Go, который позволяет собирать кастомные метрики, выполняя любые shell-команды.
Expand All @@ -26,9 +12,6 @@ PG-Bash Exporter — это конфигурируемый экспортер д
- [Конфигурация](#конфигурация)
- [Использование](#использование)
- [Документация для пользователей](#документация-для-пользователей)
- [Вклад в проект (Contributing)](#вклад-в-проект-contributing)
- [Лицензия](#лицензия)

---

## Введение
Expand Down Expand Up @@ -220,6 +203,45 @@ PG-Bash Exporter — это конфигурируемый экспортер д

После добавления этого блока и перезапуска Prometheus он начнет автоматически опрашивать ваш экспортер по адресу `/metrics`.

### Запуск полного стенда для разработки (Docker Compose)

Хотите увидеть, как экспортер работает в связке с настоящим Prometheus и Grafana? Мы подготовили все необходимое, чтобы вы могли запустить полный стенд одной командой.

**Что для этого нужно:**
Вам понадобится установленный и запущенный **Docker**.

**Как запустить:**

1. Перейдите в директорию `demo` в корне проекта:
```sh
cd demo
```

2. Выполните команду:
```sh
docker compose up --build -d
```
Эта команда соберет образ для экспортера, скачает Prometheus и Grafana и запустит все три сервиса в фоновом режиме.

**Что вы получите:**

После запуска у вас будут работать три сервиса:
* **Prometheus**: `http://localhost:9090`
* **Grafana**: `http://localhost:3000` (логин/пароль: `admin`/`admin`)
* **Ваш экспортер**: `http://localhost:8080`

Когда вы впервые зайдете в Grafana, вы увидите, что мы уже настроили для вас:
1. **Источник данных Prometheus** — Grafana уже знает, где находится ваш Prometheus.
2. **Готовый дашборд** с названием `Bash Exporter Metrics`, на котором отображаются основные метрики из вашего конфига и метрики здоровья самого экспортера.

**Как все остановить:**

Когда закончите, выполните эту команду в той же директории `demo`:
```sh
docker compose down
```
Она аккуратно остановит и удалит все контейнеры, созданные нашим стендом.

## Документация для пользователей

* [**Решение проблем (TROUBLESHOOTING.md)**](./TROUBLESHOOTING.md) — Что делать, если что-то пошло не так.
Expand Down
2 changes: 1 addition & 1 deletion configs/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ logging:

global:
# Default timeout for commands if not specified per-metric.
timeout: "15s"
timeout: "8s"
# Default cache duration for command output if not specified per-metric.
cache_ttl: "3m"
# Maximum number of commands to run concurrently during a scrape.
Expand Down
26 changes: 26 additions & 0 deletions demo/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
FROM golang:1.21-alpine AS builder

RUN apk add --no-cache git

WORKDIR /app


COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 go build -v -o /pg-bash-exporter ./cmd/exporter


FROM alpine:latest

RUN apk add --no-cache bash

COPY --from=builder /pg-bash-exporter /usr/local/bin/pg-bash-exporter

COPY configs/config.example.yaml /etc/pg-bash-exporter/config.yaml

ENTRYPOINT [ "pg-bash-exporter" ]

CMD [ "--config", "/etc/pg-bash-exporter/config.yaml" ]
53 changes: 53 additions & 0 deletions demo/dashboard.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"dashboard": {
"id": null,
"uid": null,
"title": "Bash Exporter Metrics",
"panels": [
{
"title": "System Load Average",
"type": "graph",
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 0},
"targets": [
{"expr": "system_load_load_1m"},
{"expr": "system_load_load_5m"},
{"expr": "system_load_load_15m"}
]
},
{
"title": "Process Count",
"type": "graph",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"targets": [
{"expr": "process_count"}
]
},
{
"title": "Disk Usage (Used Bytes)",
"type": "graph",
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"targets": [
{"expr": "disk_usage_used_bytes"}
]
},
{
"title": "Exporter Command Errors",
"type": "graph",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
"targets": [
{"expr": "rate(pg_bash_exporter_command_errors_total[5m])"}
]
},
{
"title": "Exporter Cache Efficiency",
"type": "graph",
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 16},
"targets": [
{"expr": "pg_bash_exporter_cache_hits_total", "legendFormat": "Cache Hits"},
{"expr": "pg_bash_exporter_cache_misses_total", "legendFormat": "Cache Misses"}
]
}
]
},
"overwrite": true
}
29 changes: 29 additions & 0 deletions demo/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
version: '3.8'

services:
exporter:
build:
context: ..
dockerfile: demo/Dockerfile
container_name: pg-bash-exporter
restart: unless-stopped
ports:
- "8080:8080"
volumes:
- ../configs/config.example.yaml:/etc/pg-bash-exporter/config.yaml

prometheus:
image: prom/prometheus:v2.45.0
container_name: prometheus
restart: unless-stopped
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml

grafana:
image: grafana/grafana:9.5.3
container_name: grafana
restart: unless-stopped
ports:
- "3000:3000"
11 changes: 11 additions & 0 deletions demo/prometheus.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
global:
scrape_interval: 15s

scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']

- job_name: 'bash_exporter'
static_configs:
- targets: ['exporter:8080']
8 changes: 4 additions & 4 deletions internal/collector/internal_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var (

func init() {
Checks = prometheus.NewCounter(prometheus.CounterOpts{
Name: "pg_bash_exporter_checks.",
Name: "pg_bash_exporter_checks_total",
Help: "Number of metrics checks.",
})

Expand All @@ -31,17 +31,17 @@ func init() {
})

CommandErrors = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "pg_bash_exporter_command_errors.",
Name: "pg_bash_exporter_command_errors_total",
Help: "Number of command errors.",
}, []string{"metric_name"})

CacheHits = prometheus.NewCounter(prometheus.CounterOpts{
Name: "pg_bash_exporter_cache_hits",
Name: "pg_bash_exporter_cache_hits_total",
Help: "Number of cache hits.",
})

CacheMisses = prometheus.NewCounter(prometheus.CounterOpts{
Name: "pg_bash_exporter_cache_misses",
Name: "pg_bash_exporter_cache_misses_total",
Help: "Number of cache misses.",
})
}