Логотип K8s Prometheus Troubleshooting

K8s Prometheus Troubleshooting

Организация
k8s-servant
k8s-prometheus-troubleshooting

Используйте этот навык, если Prometheus в Kubernetes не собирает метрики или не отправляет оповещения как ожидалось: цели ServiceMonitor или PodMonitor так и не появляются, цели недоступны ("server returned HTTP status 404 Not Found", "connection refused", "context deadline exceeded"), PrometheusRule не загружается или оповещения не срабатывают либо не доходят до Alertmanager, пользовательский ресурс Prometheus или Alertmanager не имеет статуса Available, Prometheus Operator выдаёт события "InvalidConfiguration" или поды Prometheus завершаются с OOMKilled либо из-за нехватки места на диске. Навык охватывает Prometheus Operator (kube-prometheus, kube-prometheus-stack). Проводит диагностику с помощью kubectl get, describe, events, logs и HTTP API Prometheus через API-сервер, а также предлагает решения. Сначала только изучает ситуацию и спрашивает разрешение, прежде чем что-либо менять.

Обзор

Издательk8s-servant
Репозиторийk8s-skills
Название навыкаk8s-prometheus-troubleshooting
Звёзды
36
Форки
7
Файлы в комплекте
4
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 4

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — k8s-servant. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ K8s Prometheus Troubleshooting в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/k8s-servant/k8s-skills/tree/main/skills/k8s-prometheus-troubleshooting
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/k8s-servant/k8s-skills.git /tmp/k8s-skills
mkdir -p .claude/skills
cp -r /tmp/k8s-skills/skills/k8s-prometheus-troubleshooting .claude/skills/k8s-prometheus-troubleshooting
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык K8s Prometheus Troubleshooting в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык K8s Prometheus Troubleshooting, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык K8s Prometheus Troubleshooting не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Prometheus troubleshooting

Find out why Prometheus does not scrape a target, does not load a rule, or does not alert, and propose a fix. Read first, ask before changing. Run the investigation commands freely. Run a command under an "Ask first" line only after the user approves that exact command; if your credentials do not allow it, give it to the user to run. Never run a "Proposed fix"; hand it to the user.

With the Prometheus Operator, a Prometheus custom resource selects ServiceMonitors, PodMonitors, Probes, ScrapeConfigs and PrometheusRules by label and namespace, and the operator turns them into Prometheus' configuration. A ServiceMonitor selects Services by label and names one of their ports. Something can go wrong at each step: the selection, the Service, the port, the scrape itself.

The commands use placeholders: monitoring (where Prometheus runs), my-prometheus (the Prometheus resource), my-namespace, my-app (the ServiceMonitor and its Service) and my-rules. Replace them with the real names. Prometheus' HTTP API is reached through the API server's service proxy on the governing Service prometheus-operated (port name web); this needs get on services/proxy, which the built-in view role does not have. If the proxy is forbidden, say so and ask the user for the Targets page of the Prometheus UI.

Never read Secrets. The operator stores the generated Prometheus and Alertmanager configuration in Secrets (prometheus-<name>, alertmanager-<name>-generated), and the upstream troubleshooting guide decodes them. Do not: use the selection rules, the operator's events and logs, and Prometheus' own API instead. For the same reason never call Prometheus' /api/v1/status/config or Alertmanager's /api/v2/status: they return that generated configuration (credentials masked, but webhook URLs and routes not). Access to the service proxy covers the whole Service, so this rule is yours to keep.

When to use

  • A new ServiceMonitor or PodMonitor shows no targets, or the job is missing.
  • Targets are down.
  • A PrometheusRule's alerts do not appear, do not fire, or do not reach Alertmanager.
  • The Prometheus or Alertmanager resource is not Available, or its pods crash.

Hand-offs, by skill name. When the evidence points elsewhere, continue with that skill; if it is not installed, keep going with the steps here and tell the user which skill would help:

  • The target's pods are not running or not Ready: k8s-workload-troubleshooting.
  • The target is up but a NetworkPolicy or DNS blocks the scrape: k8s-network-troubleshooting.
  • Prometheus' volume is full or will not bind: k8s-storage-troubleshooting.

Investigate

Work through the steps in order. Stop when you have the cause and its evidence.

1. Read the Prometheus resource: its status, and which monitors and rules it selects.

bash
kubectl get prometheuses -A
kubectl get prometheus my-prometheus -n monitoring -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}{.spec.serviceMonitorNamespaceSelector}{"\n"}{.spec.podMonitorSelector}{"\n"}{.spec.ruleSelector}{"\n"}{.spec.ruleNamespaceSelector}{"\n"}{.status.conditions}{"\n"}'

2. Read the ServiceMonitor and compare it with the selection and with the Service.

bash
kubectl get servicemonitors,podmonitors -A
kubectl get servicemonitor my-app -n my-namespace -o yaml
kubectl get service my-app -n my-namespace -o jsonpath='{.metadata.labels}{"\n"}{.spec.ports}{"\n"}'
kubectl get endpointslices -n my-namespace -l kubernetes.io/service-name=my-app
kubectl get namespace my-namespace --show-labels

3. Ask Prometheus what it scrapes: the jobs it has, the active targets with their health and last error, and the targets it dropped.

bash
kubectl get --raw '/api/v1/namespaces/monitoring/services/prometheus-operated:web/proxy/api/v1/scrape_pools'
kubectl get --raw '/api/v1/namespaces/monitoring/services/prometheus-operated:web/proxy/api/v1/targets?state=active' | jq -r '.data.activeTargets[] | [.labels.job, .health, .scrapeUrl, .lastError] | @tsv'
kubectl get --raw '/api/v1/namespaces/monitoring/services/prometheus-operated:web/proxy/api/v1/targets?state=dropped' | jq -r '.data.droppedTargets[].discoveredLabels | [.__meta_kubernetes_service_name, .__meta_kubernetes_endpoint_port_name, .__address__] | @tsv'

A ServiceMonitor appears as the job serviceMonitor/<namespace>/<name>/<endpoint index>.

4. Read the operator's events and logs. The operator rejects invalid objects with an event and logs objects it skips.

bash
kubectl events -n my-namespace --for servicemonitor/my-app
kubectl get deployments -A -l app.kubernetes.io/name=prometheus-operator
kubectl logs -n monitoring deployment/prometheus-operator --tail=200 | grep -i -E "skipping|rejected|my-app"

5. Open the matching reference and follow its steps:

What you seeReference
No job or no targets for a ServiceMonitor or PodMonitor, dropped targetsreferences/discovery.md
Targets down: HTTP status, connection refused, timeouts, body size, content typereferences/targets-down.md
A PrometheusRule not loaded, alerts not firing or not reaching Alertmanagerreferences/rules-and-alerts.md
The Prometheus resource not Available, pods OOMKilled, disk full, ingestion errorsreferences/prometheus-health.md

Read the results

What the common findings mean (Prometheus Operator 0.94, Prometheus 3.14):

  • No job serviceMonitor/<ns>/<name>/... in scrape_pools: the Prometheus does not select the ServiceMonitor. Its labels do not match serviceMonitorSelector, or its namespace does not match serviceMonitorNamespaceSelector. An empty selector ({}) matches everything; an unset (null) selector matches nothing for monitors and rules, and only Prometheus' own namespace for the namespace selectors.
  • The job exists, no active targets, a dropped target: the ServiceMonitor matches a Service, but its endpoints[].port is not the name of one of the Service's ports (it must be the port's name, not its number), or the Service has no ready endpoints. The dropped target's __meta_kubernetes_endpoint_port_name shows the real port name.
  • The job exists, no targets at all, nothing dropped: spec.selector matches no Service, or namespaceSelector leaves the Service's namespace out.
  • A target down with server returned HTTP status 404 Not Found: the path is wrong (endpoints[].path, default /metrics). Other lastError values are in references/targets-down.md.
  • An event InvalidConfiguration, "<name>" was rejected due to invalid configuration: ...: the operator refused the object; the message says why.

State the cause in one sentence, then the evidence you saw (the selector and labels, the port names, the target's health and error), then the proposed fix.

Proposed fix

Show each fix to the user before running it: what it changes and how to undo it. Patching a ServiceMonitor, PodMonitor or PrometheusRule (labels, port, path) is reversible, so it goes under "Ask first" and runs only after the user says yes. Changing the Prometheus or Alertmanager resource (selectors, resources, retention), Alertmanager's configuration and anything with Secrets are never run by you: hand them to the user as proposed fixes. Monitors usually come from the app's Helm chart or manifests; fix them there too. Write each undo with the values you found.

Give a ServiceMonitor the label the Prometheus selects:

Ask first: the agent runs this only after the user approves it.

bash
kubectl label servicemonitor my-app -n my-namespace release=my-prometheus
# Undo: kubectl label servicemonitor my-app -n my-namespace release-

Point a ServiceMonitor at the Service's real port name:

Ask first: the agent runs this only after the user approves it.

bash
kubectl patch servicemonitor my-app -n my-namespace --type=json -p '[{"op": "replace", "path": "/spec/endpoints/0/port", "value": "http"}]'
# Undo: kubectl patch servicemonitor my-app -n my-namespace --type=json -p '[{"op": "replace", "path": "/spec/endpoints/0/port", "value": "metrics"}]'

Prometheus picks up the change by itself within a minute or two; check scrape_pools and the targets again.

Sources

Checked against the Prometheus Operator 0.94 and Prometheus 3.14 documentation and source:

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ K8s Prometheus Troubleshooting?

Используйте этот навык, если Prometheus в Kubernetes не собирает метрики или не отправляет оповещения как ожидалось: цели ServiceMonitor или PodMonitor так и не появляются, цели недоступны ("server returned HTTP status 404 Not Found", "connection refused", "context deadline exceeded"), PrometheusRule не загружается или оповещения не срабатывают либо не доходят до Alertmanager, пользовательский ресурс Prometheus или Alertmanager не имеет статуса Available, Prometheus Operator выдаёт события "InvalidConfiguration" или поды Prometheus завершаются с OOMKilled либо из-за нехватки места на диске....

Зачем использовать K8s Prometheus Troubleshooting в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. K8s Prometheus Troubleshooting — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить K8s Prometheus Troubleshooting в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/k8s-servant/k8s-skills/tree/main/skills/k8s-prometheus-troubleshooting. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать K8s Prometheus Troubleshooting?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать K8s Prometheus Troubleshooting?

С любым количеством. В TypingMind вы можете использовать K8s Prometheus Troubleshooting с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ K8s Prometheus Troubleshooting?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — k8s-servant. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇