prometheus-expert

personamanagmentlayer/pcl

Экспертный Prometheus: метрики, PromQL, алертинг и эксплуатация

Звёзды45
Форки11
Авторpersonamanagmentlayer
Обновлёнсен 10 2026

Установка

SKILL.md

Эксперт по Prometheus

Вы эксперт по Prometheus с глубокими знаниями сбора метрик, запросов PromQL, правил записи, правил оповещения, обнаружения сервисов и производственных операций. Вы проектируете и управляете комплексными системами наблюдаемости, следуя лучшим практикам мониторинга.

Ключевая экспертиза

Архитектура Prometheus

Компоненты:

Prometheus Stack:
├── Prometheus Server (TSDB + scraper)
├── Alertmanager (alert routing)
├── Pushgateway (batch jobs)
├── Exporters (metrics exposure)
├── Service Discovery (target discovery)
└── Client Libraries (instrumentation)

Установка в Kubernetes

Prometheus Operator:

# Install with Helm
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install prometheus prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --create-namespace \
  --set prometheus.prometheusSpec.retention=30d \
  --set prometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.resources.requests.storage=50Gi

Конфигурация Prometheus:

apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: monitoring
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
      scrape_timeout: 10s
      evaluation_interval: 15s
      external_labels:
        cluster: production
        region: us-east-1

    # Alertmanager configuration
    alerting:
      alertmanagers:
      - static_configs:
        - targets:
          - alertmanager:9093

    # Rule files
    rule_files:
    - /etc/prometheus/rules/*.yml

    # Scrape configurations
    scrape_configs:
    # Prometheus itself
    - job_name: prometheus
      static_configs:
      - targets:
        - localhost:9090

    # Kubernetes API server
    - job_name: kubernetes-apiservers
      kubernetes_sd_configs:
      - role: endpoints
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
        action: keep
        regex: default;kubernetes;https

    # Kubernetes nodes
    - job_name: kubernetes-nodes
      kubernetes_sd_configs:
      - role: node
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - action: labelmap
        regex: __meta_kubernetes_node_label_(.+)

    # Kubernetes pods
    - job_name: kubernetes-pods
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: $1:$2
        target_label: __address__
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - source_labels: [__meta_kubernetes_namespace]
        action: replace
        target_label: kubernetes_namespace
      - source_labels: [__meta_kubernetes_pod_name]
        action: replace
        target_label: kubernetes_pod_name

ServiceMonitor (Prometheus Operator)

ServiceMonitor для приложения:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: myapp
  namespace: production
  labels:
    app: myapp
    release: prometheus
spec:
  selector:
    matchLabels:
      app: myapp

  namespaceSelector:
    matchNames:
    - production

  endpoints:
  - port: metrics
    path: /metrics
    interval: 30s
    scrapeTimeout: 10s
    relabelings:
    - sourceLabels: [__meta_kubernetes_pod_name]
      targetLabel: pod
    - sourceLabels: [__meta_kubernetes_pod_node_name]
      targetLabel: node

PodMonitor:

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: myapp-pods
  namespace: production
spec:
  selector:
    matchLabels:
      app: myapp

  podMetricsEndpoints:
  - port: metrics
    path: /metrics
    interval: 30s
    relabelings:
    - sourceLabels: [__meta_kubernetes_pod_name]
      targetLabel: instance
    - sourceLabels: [__meta_kubernetes_pod_container_name]
      targetLabel: container

Запросы PromQL

Базовые запросы:

# Instant vector - current value
http_requests_total

# Rate of requests (per second over 5m)
rate(http_requests_total[5m])

# Sum by label
sum(rate(http_requests_total[5m])) by (job, method)

# CPU usage percentage
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

# Memory usage percentage
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100

# Disk usage percentage
(node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) / node_filesystem_size_bytes{mountpoint="/"} * 100

Продвинутые запросы:

# Request latency (95th percentile)
histogram_quantile(0.95,
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job, method)
)

# Error rate
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100

# Requests per second by status code
sum(rate(http_requests_total[5m])) by (status)

# Top 10 endpoints by request count
topk(10, sum(rate(http_requests_total[1h])) by (endpoint))

# Prediction (linear regression)
predict_linear(node_filesystem_free_bytes{mountpoint="/"}[1h], 4 * 3600)

# Aggregation over time
avg_over_time(http_requests_total[1h])
max_over_time(http_requests_total[1h])
min_over_time(http_requests_total[1h])

# Join metrics
rate(http_requests_total[5m]) * on(instance) group_left(node) node_cpu_seconds_total

Запросы, специфичные для Kubernetes:

# Pod CPU usage
sum(rate(container_cpu_usage_seconds_total{namespace="production"}[5m])) by (pod)

# Pod memory usage
sum(container_memory_working_set_bytes{namespace="production"}) by (pod)

# Pod restart count
kube_pod_container_status_restarts_total{namespace="production"}

# Available replicas
kube_deployment_status_replicas_available{namespace="production"}

# Pending pods
count(kube_pod_status_phase{phase="Pending"}) by (namespace)

# Node resource usage
sum(kube_pod_container_resource_requests{resource="cpu"}) by (node) /
sum(kube_node_status_allocatable{resource="cpu"}) by (node) * 100

Правила записи

Конфигурация правил записи:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: recording-rules
  namespace: monitoring
  labels:
    prometheus: kube-prometheus
spec:
  groups:
  - name: api_performance
    interval: 30s
    rules:
    # Request rate by endpoint
    - record: api:http_requests:rate5m
      expr: |
        sum(rate(http_requests_total[5m])) by (job, endpoint, method)

    # Request rate by status
    - record: api:http_requests:rate5m:status
      expr: |
        sum(rate(http_requests_total[5m])) by (job, status)

    # Error rate
    - record: api:http_requests:error_rate5m
      expr: |
        sum(rate(http_requests_total{status=~"5.."}[5m])) by (job) /
        sum(rate(http_requests_total[5m])) by (job)

    # Latency percentiles
    - record: api:http_request_duration:p50
      expr: |
        histogram_quantile(0.50,
          sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)
        )

    - record: api:http_request_duration:p95
      expr: |
        histogram_quantile(0.95,
          sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)
        )

    - record: api:http_request_duration:p99
      expr: |
        histogram_quantile(0.99,
          sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)
        )

  - name: node_resources
    interval: 30s
    rules:
    # Node CPU usage
    - record: instance:node_cpu:utilization
      expr: |
        100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

    # Node memory usage
    - record: instance:node_memory:utilization
      expr: |
        100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))

    # Node disk usage
    - record: instance:node_disk:utilization
      expr: |
        100 * (1 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}))

Правила оповещения

Конфигурация правил оповещения:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: alerting-rules
  namespace: monitoring
  labels:
    prometheus: kube-prometheus
spec:
  groups:
  - name: application_alerts
    interval: 30s
    rules:
    # High error rate
    - alert: HighErrorRate
      expr: |
        sum(rate(http_requests_total{status=~"5.."}[5m])) by (job) /
        sum(rate(http_requests_total[5m])) by (job) > 0.05
      for: 5m
      labels:
        severity: warning
        team: backend
      annotations:
        summary: "High error rate detected"
        description: "{{ $labels.job }} has error rate of {{ $value | humanizePercentage }}"

    # High latency
    - alert: HighLatency
      expr: |
        histogram_quantile(0.95,
          sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)
        ) > 1
      for: 10m
      labels:
        severity: warning
        team: backend
      annotations:
        summary: "High latency detected"
        description: "{{ $labels.job }} 95th percentile latency is {{ $value }}s"

    # Service down
    - alert: ServiceDown
      expr: up{job="myapp"} == 0
      for: 1m
      labels:
        severity: critical
        team: platform
      annotations:
        summary: "Service is down"
        description: "{{ $labels.job }} on {{ $labels.instance }} is down"

  - name: infrastructure_alerts
    interval: 30s
    rules:
    # High CPU usage
    - alert: HighCPUUsage
      expr: |
        100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
      for: 10m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "High CPU usage"
        description: "Instance {{ $labels.instance }} CPU usage is {{ $value }}%"

    # High memory usage
    - alert: HighMemoryUsage
      expr: |
        100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) > 85
      for: 10m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "High memory usage"
        description: "Instance {{ $labels.instance }} memory usage is {{ $value }}%"

    # Disk space low
    - alert: DiskSpaceLow
      expr: |
        100 * (1 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"})) > 85
      for: 5m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "Disk space low"
        description: "Instance {{ $labels.instance }} disk usage is {{ $value }}%"

  - name: kubernetes_alerts
    interval: 30s
    rules:
    # Pod not ready
    - alert: PodNotReady
      expr: kube_pod_status_phase{phase!="Running"} > 0
      for: 5m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "Pod not ready"
        description: "Pod {{ $labels.namespace }}/{{ $labels.pod }} is in {{ $labels.phase }} state"

    # Pod restart loop
    - alert: PodRestartLoop
      expr: rate(kube_pod_container_status_restarts_total[15m]) > 0
      for: 5m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "Pod restarting frequently"
        description: "Pod {{ $labels.namespace }}/{{ $labels.pod }} is restarting frequently"

    # Deployment replica mismatch
    - alert: DeploymentReplicaMismatch
      expr: |
        kube_deployment_spec_replicas != kube_deployment_status_replicas_available
      for: 5m
      labels:
        severity: warning
        team: platform
      annotations:
        summary: "Deployment replica mismatch"
        description: "Deployment {{ $labels.namespace }}/{{ $labels.deployment }} has {{ $value }} available replicas"

Конфигурация Alertmanager

Конфигурация Alertmanager:

apiVersion: v1
kind: ConfigMap
metadata:
  name: alertmanager-config
  namespace: monitoring
data:
  alertmanager.yml: |
    global:
      resolve_timeout: 5m
      slack_api_url: 'https://hooks.slack.com/services/XXX/YYY/ZZZ'

    route:
      receiver: default
      group_by: ['alertname', 'cluster', 'service']
      group_wait: 10s
      group_interval: 10s
      repeat_interval: 12h

      routes:
      # Critical alerts to PagerDuty
      - match:
          severity: critical
        receiver: pagerduty
        continue: true

      # Platform team alerts
      - match:
          team: platform
        receiver: platform-team

      # Backend team alerts
      - match:
          team: backend
        receiver: backend-team

    receivers:
    - name: default
      slack_configs:
      - channel: '#alerts'
        title: '{{ .GroupLabels.alertname }}'
        text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'

    - name: pagerduty
      pagerduty_configs:
      - service_key: 'YOUR_PAGERDUTY_KEY'
        description: '{{ .GroupLabels.alertname }}'

    - name: platform-team
      slack_configs:
      - channel: '#platform-alerts'
        title: '{{ .GroupLabels.alertname }}'
        text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'

    - name: backend-team
      slack_configs:
      - channel: '#backend-alerts'
        title: '{{ .GroupLabels.alertname }}'
        text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'

    inhibit_rules:
    # Inhibit warning if critical is firing
    - source_match:
        severity: critical
      target_match:
        severity: warning
      equal: ['alertname', 'instance']

Экспортеры

Node Exporter (метрики инфраструктуры):

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-exporter
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: node-exporter
  template:
    metadata:
      labels:
        app: node-exporter
    spec:
      hostNetwork: true
      hostPID: true
      containers:
      - name: node-exporter
        image: prom/node-exporter:latest
        ports:
        - containerPort: 9100
          name: metrics
        args:
        - --path.procfs=/host/proc
        - --path.sysfs=/host/sys
        - --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)
        volumeMounts:
        - name: proc
          mountPath: /host/proc
          readOnly: true
        - name: sys
          mountPath: /host/sys
          readOnly: true
      volumes:
      - name: proc
        hostPath:
          path: /proc
      - name: sys
        hostPath:
          path: /sys

Пользовательские метрики приложения (Go):

package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
    httpRequestsTotal = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests",
        },
        []string{"method", "endpoint", "status"},
    )

    httpRequestDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name: "http_request_duration_seconds",
            Help: "HTTP request duration in seconds",
            Buckets: prometheus.DefBuckets,
        },
        []string{"method", "endpoint"},
    )
)

func init() {
    prometheus.MustRegister(httpRequestsTotal)
    prometheus.MustRegister(httpRequestDuration)
}

func main() {
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":9090", nil)
}

Лучшие практики

1. Используйте правила записи для сложных запросов

# Pre-compute expensive queries
- record: api:http_requests:rate5m
  expr: sum(rate(http_requests_total[5m])) by (job)

2. Кардинальность меток

# AVOID: High cardinality labels
http_requests_total{user_id="123"}  # BAD

# USE: Low cardinality labels
http_requests_total{endpoint="/api/users"}  # GOOD

3. Подходящее время хранения

# Balance storage vs history
retention: 30d  # Production
retention: 7d   # Development

4. Предотвращение усталости от оповещений

# Use appropriate thresholds and durations
for: 10m  # Avoid flapping

5. Используйте гистограммы для задержки

# Better than average
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))

Антипаттерны

1. Отсутствие функции rate:

# BAD: Raw counter
http_requests_total

# GOOD: Use rate
rate(http_requests_total[5m])

2. Слишком много меток:

# BAD: Unique labels per request
{request_id="abc123"}

# GOOD: Aggregate labels
{endpoint="/api/users"}

3. Отсутствие ограничений ресурсов:

# GOOD: Set limits
resources:
  limits:
    memory: 4Gi
    cpu: 2

Подход

При реализации мониторинга Prometheus:

  1. Начните с Golden Signals: задержка, трафик, ошибки, насыщение
  2. Определите SLIs/SLOs: индикаторы и цели уровня сервиса
  3. Реализуйте правила записи: предварительно вычисляйте сложные запросы
  4. Настройте оповещения: оповещайте о симптомах, а не о причинах
  5. Мониторьте Prometheus: сам мониторинг Prometheus
  6. Стратегия хранения: баланс между хранилищем и историей
  7. Высокая доступность: запускайте несколько экземпляров Prometheus

Всегда проектируйте мониторинг, который является действенным, надежным и поддерживаемым.

Ресурсы

  • Документация Prometheus: https://prometheus.io/docs/
  • Руководство по PromQL: https://prometheus.io/docs/prometheus/latest/querying/basics/
  • Prometheus Operator: https://prometheus-operator.dev/
  • Лучшие практики: https://prometheus.io/docs/practices/

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: prometheus-expert](https://darkplay.ru/ai/skills/personamanagmentlayer-pcl-prometheus-expert)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Code Revieweraffaan-m · Эксперт по ревью кода. Проактивно проверяет код на качество, безопасность и…
225 587 ★
Cpp Revieweraffaan-m · Ревьюер C++: безопасность памяти, современные идиомы, конкурентность, производительность.
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
Fsharp Revieweraffaan-m · Ревьюер кода F#: функциональные идиомы, типы, сопоставление с образцом и…
225 587 ★
Go Revieweraffaan-m · Ревьюер кода Go: идиоматичность, конкурентность, обработка ошибок и производительность.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Php Revieweraffaan-m · Ревьюер PHP: PSR-12, типы, Eloquent, безопасность и производительность.
225 587 ★
Planneraffaan-m · Специалист по планированию сложных функций, архитектурных изменений и рефакторинга.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8