К основному содержанию
скилл CX Codex

pyroscope — скилл для Claude Code: непрерывное профилирование

Скилл для непрерывного профилирования приложений через Grafana Pyroscope: флейм-графы CPU, памяти и аллокаций прямо в диалоге с агентом.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add grafana/skills --skill pyroscope -a claude-code
Открыть на GitHub

Что делает pyroscope

Скилл описывает три пути подключения инструментирования: SDK языка (Go, Java, Python, Ruby, Node, .NET, Rust) шлёт данные напрямую в Pyroscope, Alloy с eBPF собирает профили без правок кода, либо SDK отправляет их в pyroscope.receive_http, а Alloy пересылает дальше. Внутри — примеры конфигурации Python SDK, блок config.alloy для кластерного eBPF-профилирования, запросы на ProfileQL и разбор типов профилей: CPU, память, аллокации, горутины, мьютексы.

Для eBPF через Alloy нужны root, доступ к PID хоста и Linux ядра 5.8 и выше с BTF (или RHEL 4.18+). Для Grafana Cloud Profiles понадобятся числовой Pyroscope user (stack id) и API key. Если ядро старше или BTF нет, компонент pyroscope.ebpf уйдёт в состояние unhealthy с ошибками BPF — это повод проверить ls /sys/kernel/btf/vmlinux до того, как разворачивать сбор на весь кластер.

Скилл также закрывает связку Span Profiles: медленный трейс в Tempo сопоставляется с профилем, и видно, какой участок кода его тормозит. Есть раздел с типовыми сбоями: SDK запустился, а флейм-графа нет; Cloud отдаёт 401 из-за неверного basic_auth_username; профиль приходит без фреймов — для Java нужен PYROSCOPE_FORMAT=jfr, для Python на Alpine проверяется совместимость procfs и glibc.

Какие задачи решает

  • найти, что съедает CPU в сервисе, по флейм-графу
  • сравнить два профиля и поймать регрессию
  • развернуть кластерное профилирование через Alloy без правок кода
  • связать медленный трейс Tempo с профилем кода
  • разобраться, почему так высоко потребление памяти и аллокаций

Примеры запросов агенту

  • добавь профилирование Pyroscope в этот Python-сервис
  • настрой Alloy как eBPF-профайлер для всего кластера
  • сравни два профиля CPU и покажи, где регрессия

Как установить pyroscope

1Через Skills CLI (Vercel)

npx skills add grafana/skills --skill pyroscope -a claude-code

2Вручную: положить файлы

~/.claude/skills/pyroscope/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/pyroscope/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора44

alerting-irm Настраивает Grafana Alerting, IRM и SLO: от правил и маршрутизации до дежурств и эскалаций. Пригодится для YAML- и API-конфигурации. CX Codex +1 5 100установок assistant-mcp Помогает подключить ИИ-агентов к Grafana Cloud через MCP-сервер mcp-grafana. Пригодится для чтения метрик, поиска дашбордов и проверки алертов прямо в кодовой базе. CX Codex +1 5 000установок alloy Помогает писать и проверять конфиги Grafana Alloy: сбор метрик, логов, трейсов и профилей в один пайплайн. CX Codex +1 5 000установок tempo Скилл для развёртывания Grafana Tempo и написания запросов TraceQL: от локального Docker Compose до Helm в Kubernetes. CX Codex +1 4 900установок beyla Автоматически подключает eBPF-мониторинг HTTP, gRPC и баз данных через Grafana Beyla без изменения кода. Пригодится для сбора трейсов и RED-метрик с готовых бинарников. CX Codex +1 4 700установок infrastructure Настраивает передачу метрик, логов и трейсов из Kubernetes, Linux-хостов и облаков в Grafana Cloud. Пригодится при подключении кластеров и виртуалок. CX Codex +1 4 300установок dpm-finder Скилл помогает найти метрики Prometheus с наибольшим числом точек в минуту в Grafana Cloud и выявить причины растущих расходов на мониторинг. CX Codex +1 4 200установок oncall-irm Помогает агенту настроить маршрутизацию алертов, дежурные ротации и жизненный цикл инцидентов в Grafana IRM / OnCall. CX Codex +1 4 200установок

Похожие

monitor-setup Seth Hobson Слэш-команда, которая разворачивает сбор метрик Prometheus, дашборды Grafana, распределённую трассировку и агрегацию логов. CX Codex ★ 41 729звёзд репо grafana-dashboards Seth Hobson Скилл помогает создавать Grafana-дашборды для метрик систем и приложений. Подойдёт для мониторинга, SLO и операционных интерфейсов наблюдаемости. CX Codex 13 097установок qdrant-monitoring qdrant Скилл подсказывает, как настроить мониторинг Qdrant и разобраться с зависшим оптимизатором, ростом памяти или медленными запросами. CX Codex +1 1 500установок grafana-dashboard aj-geddes Помогает агенту собирать дашборды Grafana: панели, переменные, алерты и провижининг. Пригодится, когда нужно быстро накидать мониторинг по метрикам. CX Codex +1 494установок monitoring-observability ahmedasmar Скилл для настройки мониторинга и наблюдаемости: стратегия метрик, алерты, дашборды, SLO и разбор инцидентов. CX Codex +1 493установок loki-logging devops-skills Скилл помогает настроить Grafana Loki, Promtail и запросы LogQL прямо в проекте, без похода в документацию. CX Codex +1 330установок

Рядом в теме «DevOps и инфраструктура»

Всё по теме «DevOps и инфраструктура» →

Вопросы о pyroscope

Как установить pyroscope в Claude?

Выполните npx skills add grafana/skills --skill pyroscope -a claude-code. Скилл появится в ~/.claude/skills/pyroscope/SKILL.md.

Что делает скилл pyroscope?

Помогает подключить непрерывное профилирование через Grafana Pyroscope и читать результат как флейм-графы. Покрывает SDK, eBPF через Alloy, запросы ProfileQL и связку трейсов с профилями.

Что нужно для eBPF-профилирования через Alloy?

Root, доступ к PID хоста и Linux ядра 5.8 и выше с BTF (или RHEL 4.18+). Без этого компонент pyroscope.ebpf будет нездоров.

Исходный текст

SKILL.md · Apache-2.0
---
name: pyroscope
license: Apache-2.0
description: Continuously profile applications with Grafana Pyroscope and read the result as flame graphs. Covers three instrumentation paths — language SDK push (Go / Java / Python / Ruby / Node / .NET / Rust), Alloy eBPF auto-instrumentation (no code change, requires kernel 5.8+ with BTF), and SDK → Alloy receiver — plus ProfileQL queries, profile types (CPU / memory / allocations / goroutines / mutex), Grafana Cloud Profiles endpoint, and Span Profiles trace-to-profile linking. Use when adding profiling to a service, deploying Alloy as a cluster-wide eBPF profiler, hunting CPU / memory hotspots from a flame graph, comparing two profiles to find a regression, or correlating a slow Tempo trace to its profile — even when the user says "find what's burning CPU", "flame graph this app", "continuous profiling", "heap hotspots", or "why is allocation so high" without naming Pyroscope.
---

# Grafana Pyroscope

> **Docs**: https://grafana.com/docs/pyroscope/latest/

Continuous profiling — flame graphs of CPU, memory, allocations, mutex contention, goroutines.

## Prerequisites

- Pyroscope server (OSS) or Grafana Cloud Profiles endpoint
- For Cloud: numeric Pyroscope user (stack id) + API key
- For eBPF via Alloy: root + host PID + Linux ≥ 5.8 with BTF (or RHEL 4.18+)

## Instrumentation paths

1. **Alloy eBPF** (preferred) — auto-instrument, no code change
2. **SDK direct push** — application calls Pyroscope API
3. **SDK → Alloy** — SDK posts to `pyroscope.receive_http`, Alloy forwards

## Common Workflows

### 1. Instrument an app with the SDK (representative: Python)

```bash
pip install pyroscope-io==1.0.11
```

```python
import pyroscope, os
pyroscope.configure(
    application_name="my.python.app",
    server_address="http://pyroscope:4040",
    sample_rate=100, oncpu=True,
    tags={"region": os.getenv("REGION"), "env": "prod"},
)
# Dynamic tag for a hot path
with pyroscope.tag_wrapper({"controller": "slow_controller"}):
    slow_code()
```

```bash
# Verify the app is pushing — Pyroscope ingests samples in a few seconds
curl -s http://pyroscope:4040/ready                                    # → "ready"
curl -s http://pyroscope:4040/api/v1/labels | jq '.data | index("service_name")'  # → not null

# Verify the service shows up in Grafana → Explore → Profiles → service dropdown.
```

Other SDKs (Java agent, Node, Ruby, .NET, Rust) + Cloud auth + tunable env vars: [`references/sdks.md`](references/sdks.md).

### 2. Cluster-wide eBPF profiling with Alloy

```alloy
# config.alloy — full block in references/ebpf-and-query.md
pyroscope.ebpf "local_pods" {
  forward_to       = [pyroscope.write.cloud.receiver]
  targets          = discovery.relabel.local_pods.output
  sample_rate      = 97
  collect_interval = "15s"
}
pyroscope.write "cloud" {
  endpoint {
    url = "https://profiles-prod-xxx.grafana.net"
    basic_auth { username = sys.env("PYROSCOPE_USER")
                 password = sys.env("GRAFANA_API_KEY") }
  }
}
```

```bash
# 1. Reload Alloy
curl -X POST http://localhost:12345/-/reload

# 2. Verify the eBPF component is healthy
curl -s http://localhost:12345/api/v0/web/components \
  | jq '.[] | select(.id|contains("pyroscope.ebpf")) | {id,health:.health.state}'
# Expect: health.state == "healthy"

# 3. Verify profiles arriving in Pyroscope
#    Grafana → Explore → Profiles datasource → query:
#      {namespace="default", __profile_type__="process_cpu:cpu:nanoseconds:cpu:nanoseconds"}
#    Expect flame graph to render with frames from the target pods.
```

### 3. Query with ProfileQL

```
{service_name="myapp", env="prod",
 __profile_type__="process_cpu:cpu:nanoseconds:cpu:nanoseconds"}
```

Profile-type list + full ProfileQL grammar: [`references/ebpf-and-query.md`](references/ebpf-and-query.md).

## Troubleshooting

- SDK starts but no flame graph → check the app actually called `start()` / `configure()` (some SDKs are lazy); check `server_address` reachable from inside the container
- Alloy eBPF component `unhealthy` with BPF errors → kernel < 5.8 or BTF missing; `ls /sys/kernel/btf/vmlinux`
- Cloud push 401 → wrong `basic_auth_username` (must be the numeric stack id, not the slug)
- Profile shows up but with no frames → for Java, set `PYROSCOPE_FORMAT=jfr`; for Python on Alpine, ensure `procfs` and `glibc` compatibility

## Resources

- [Pyroscope docs](https://grafana.com/docs/pyroscope/latest/)
- [Grafana Cloud Profiles](https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/)
- [`references/sdks.md`](references/sdks.md) — Java/Node/Ruby/.NET/Rust install + config + env-var table + profile-type matrix
- [`references/ebpf-and-query.md`](references/ebpf-and-query.md) — full Alloy eBPF pipeline + ProfileQL

© grafana · Apache-2.0 · grafana/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой