feat: telemetry cost profile with head sampling, coarse buckets and balanced tail sampling
- [telemetry] trace_sample_ratio (ParentBased(TraceIdRatioBased), 1 keeps ParentBased(ALWAYS_ON)) and metric_buckets (default|coarse with SLO bounds), export interval <= 30 s; otel.sdk.span.started, span.live dropped; startup records name ratio, buckets and interval - bench: telemetry services on mtusi-bench, TELEMETRY=on switch for uploads and queue, make bench_telemetry[_quick] with off/full/full-aa/head/tail/ metrics/balanced, rare events, lookup from Tempo/Loki/Prometheus, cost sampler, verdicts H1-H8 and B1-B5; collector layers and lean Prometheus in bench/otel with preflight checks - REPORT: telemetry cost hypotheses and criteria before the label Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -177,7 +177,63 @@ services:
|
||||
memory: ${BENCH_LB_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_LB_MEMORY:?run make bench}
|
||||
|
||||
# сервисы телеметрии (design change track1-telemetry-cost, решения 1 и 13):
|
||||
# образы, конфигурации infra/otel/ и лимиты рабочего стенда (BENCH_* — поля
|
||||
# Profile, сверка с основным файлом до стенда), без swap, без перезапуска и
|
||||
# без портов. Запускают их только варианты профиля цены телеметрии и
|
||||
# выключатель TELEMETRY=on профилей загрузок и очереди: старт стенда
|
||||
# перечисляет сервисы. Grafana описана основным файлом и не запускается —
|
||||
# её порт сброшен, чтобы разбор стенда не занимал порт рабочего
|
||||
otel-collector:
|
||||
container_name: mtusi-bench-otel-collector
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${BENCH_COLLECTOR_CPUS:?run make bench}
|
||||
memory: ${BENCH_COLLECTOR_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_COLLECTOR_MEMORY:?run make bench}
|
||||
|
||||
prometheus:
|
||||
container_name: mtusi-bench-prometheus
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${BENCH_PROMETHEUS_CPUS:?run make bench}
|
||||
memory: ${BENCH_PROMETHEUS_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_PROMETHEUS_MEMORY:?run make bench}
|
||||
|
||||
loki:
|
||||
container_name: mtusi-bench-loki
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${BENCH_LOKI_CPUS:?run make bench}
|
||||
memory: ${BENCH_LOKI_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_LOKI_MEMORY:?run make bench}
|
||||
|
||||
tempo:
|
||||
container_name: mtusi-bench-tempo
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${BENCH_TEMPO_CPUS:?run make bench}
|
||||
memory: ${BENCH_TEMPO_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_TEMPO_MEMORY:?run make bench}
|
||||
|
||||
grafana:
|
||||
container_name: mtusi-bench-grafana
|
||||
restart: "no"
|
||||
ports: !reset []
|
||||
|
||||
networks:
|
||||
default:
|
||||
# k6 подключается к сети стенда по имени (docker run --network)
|
||||
name: mtusi-bench
|
||||
telemetry:
|
||||
# хранилища телеметрии; контейнер выборки (telemetry_lookup.py)
|
||||
# подключается к ней по имени
|
||||
name: mtusi-bench-telemetry
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
// Профиль цены телеметрии (design change track1-telemetry-cost, решение 8):
|
||||
// одинаковая открытая нагрузка ниже насыщения через LB во всех вариантах.
|
||||
// Классы — сценарии constant-arrival-rate с одним startTime на всю длину
|
||||
// прогона (разогрев + чистое окно + окно отказов), timeUnit 10 с для дробной
|
||||
// интенсивности; деление на окна — по времени отправки от t0 (setup пишет
|
||||
// «t-t0,<мс>», часы ВМ). VU заранее и без прибавления, ответ не повторяется:
|
||||
// недосланные итерации — dropped_iterations. Строка на запрос в файл консоли:
|
||||
// «t,<класс>,<отправка мс>,<длительность мс>,<статус>,<X-Request-Id>,
|
||||
// <X-Instance-Id>,<id вложения|->». Входы оркестратора: fixture.json
|
||||
// (prepare.js), downloads.json (готовые вложения разогрева), broken.json (id
|
||||
// вложения без объекта), тела s.jpg и bad.jpg (make_images.py).
|
||||
// RATES — «класс:в секунду,…» (Profile.telemetry_rates)
|
||||
// DURATION — секунды всех окон
|
||||
// NAME — имя итога в raw/
|
||||
// Регистрация: пароль — crypto.randomUUID() только в памяти итерации, в строки,
|
||||
// итог и файлы не попадает; токен ответа не читается.
|
||||
import exec from "k6/execution";
|
||||
import http from "k6/http";
|
||||
import { SharedArray } from "k6/data";
|
||||
|
||||
import {
|
||||
API,
|
||||
PAGE_LIMIT,
|
||||
SUMMARY_THRESHOLDS,
|
||||
SUMMARY_TREND_STATS,
|
||||
WORK_DIR,
|
||||
authHeaders,
|
||||
messageHeaders,
|
||||
summaryFiles,
|
||||
syntheticText,
|
||||
} from "./lib.js";
|
||||
|
||||
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
|
||||
const downloads = new SharedArray(
|
||||
"downloads",
|
||||
() => JSON.parse(open(`${WORK_DIR}/downloads.json`)),
|
||||
);
|
||||
const BROKEN = JSON.parse(open(`${WORK_DIR}/broken.json`));
|
||||
const GOOD_BODY = open(`${WORK_DIR}/s.jpg`, "b");
|
||||
const BAD_BODY = open(`${WORK_DIR}/bad.jpg`, "b");
|
||||
const DURATION = Number(__ENV.DURATION);
|
||||
const RATES = Object.fromEntries(
|
||||
(__ENV.RATES || "")
|
||||
.split(",")
|
||||
.filter((item) => item !== "")
|
||||
.map((item) => {
|
||||
const [name, rate] = item.split(":");
|
||||
return [name, Number(rate)];
|
||||
}),
|
||||
);
|
||||
// больше timeout server LB (10 с, у загрузки 30 с): клиент видит ответ LB
|
||||
const TIMEOUT = "40s";
|
||||
const READER = authHeaders(fixture.tokens[fixture.readerId]);
|
||||
const WRITE_URL = `${API}/chats/${fixture.writeChatId}/messages`;
|
||||
const UPLOAD_URL = `${API}/chats/${fixture.readChatId}/attachments`;
|
||||
|
||||
// VU заранее: интенсивность × запас на медленные ответы (запись под
|
||||
// блокировкой до 0,6 с, регистрация с Argon2id до 1 с) + постоянная часть
|
||||
function vus(rate) {
|
||||
return Math.max(4, Math.ceil(rate * 2) + 4);
|
||||
}
|
||||
|
||||
function scenarios() {
|
||||
const out = {};
|
||||
for (const [name, rate] of Object.entries(RATES)) {
|
||||
if (!(rate > 0)) {
|
||||
continue;
|
||||
}
|
||||
out[name] = {
|
||||
executor: "constant-arrival-rate",
|
||||
exec: name,
|
||||
rate: Math.max(1, Math.round(rate * 10)),
|
||||
timeUnit: "10s",
|
||||
startTime: "0s",
|
||||
duration: `${DURATION}s`,
|
||||
preAllocatedVUs: vus(rate),
|
||||
maxVUs: vus(rate),
|
||||
gracefulStop: "45s",
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const iterationThresholds = Object.fromEntries(
|
||||
Object.keys(RATES).map((name) => [
|
||||
`iterations{scenario:${name}}`,
|
||||
["count>=0"],
|
||||
]),
|
||||
);
|
||||
|
||||
export const options = {
|
||||
scenarios: scenarios(),
|
||||
summaryTrendStats: SUMMARY_TREND_STATS,
|
||||
// пороги всегда выполняются: итерации по сценариям и недосланные попадают
|
||||
// в итог, run.py сверяет с ними число строк
|
||||
thresholds: {
|
||||
...SUMMARY_THRESHOLDS,
|
||||
...iterationThresholds,
|
||||
iterations: ["count>=0"],
|
||||
dropped_iterations: ["count>=0"],
|
||||
},
|
||||
};
|
||||
|
||||
export function setup() {
|
||||
const t0 = Date.now();
|
||||
console.log(`t-t0,${t0}`);
|
||||
return { t0 };
|
||||
}
|
||||
|
||||
// длительность — монотонные тайминги k6 с точностью 0,01 мс, без ответа —
|
||||
// разность часов
|
||||
function report(kind, start, res, id = "-") {
|
||||
const t = res.timings;
|
||||
const measured = t.blocked + t.connecting + t.tls_handshaking + t.duration;
|
||||
const duration = Math.max(
|
||||
0,
|
||||
Math.round((res.status === 0 ? Date.now() - start : measured) * 100) / 100,
|
||||
);
|
||||
const requestId = res.headers["X-Request-Id"] || "-";
|
||||
const instance = res.headers["X-Instance-Id"] || "-";
|
||||
console.log(
|
||||
`t,${kind},${start},${duration},${res.status},${requestId},${instance},` +
|
||||
`${id}`,
|
||||
);
|
||||
}
|
||||
|
||||
function get(kind, url, expected) {
|
||||
const start = Date.now();
|
||||
const res = http.get(url, {
|
||||
headers: READER,
|
||||
responseType: "none",
|
||||
timeout: TIMEOUT,
|
||||
responseCallback: http.expectedStatuses(expected),
|
||||
});
|
||||
report(kind, start, res);
|
||||
}
|
||||
|
||||
export function read() {
|
||||
get("read", `${WRITE_URL}?limit=${PAGE_LIMIT}`, 200);
|
||||
}
|
||||
|
||||
export function me() {
|
||||
get("me", `${API}/users/me`, 200);
|
||||
}
|
||||
|
||||
export function card() {
|
||||
get("card", `${API}/chats/${fixture.writeChatId}`, 200);
|
||||
}
|
||||
|
||||
export function download() {
|
||||
const id = downloads[exec.scenario.iterationInTest % downloads.length];
|
||||
get("download", `${API}/attachments/${id}/content`, 200);
|
||||
}
|
||||
|
||||
// вложение без объекта: 500 AttachmentContentMissing — ожидаемый ответ класса
|
||||
export function broken() {
|
||||
get("broken", `${API}/attachments/${BROKEN}/content`, 500);
|
||||
}
|
||||
|
||||
export function write() {
|
||||
const n = exec.scenario.iterationInTest;
|
||||
const sender = fixture.memberIds[n % fixture.memberIds.length];
|
||||
const start = Date.now();
|
||||
const res = http.post(
|
||||
WRITE_URL,
|
||||
JSON.stringify({ text: syntheticText("tc", n) }),
|
||||
{
|
||||
headers: messageHeaders(fixture.tokens[sender]),
|
||||
responseType: "none",
|
||||
timeout: TIMEOUT,
|
||||
responseCallback: http.expectedStatuses(201),
|
||||
},
|
||||
);
|
||||
report("write", start, res);
|
||||
}
|
||||
|
||||
function postUpload(kind, body) {
|
||||
const start = Date.now();
|
||||
const res = http.post(`${UPLOAD_URL}?filename=bench`, body, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${fixture.tokens[fixture.readerId]}`,
|
||||
"Content-Type": "image/jpeg",
|
||||
},
|
||||
timeout: TIMEOUT,
|
||||
responseCallback: http.expectedStatuses(202),
|
||||
});
|
||||
let id = "-";
|
||||
if (res.status === 202) {
|
||||
id = res.json("id");
|
||||
}
|
||||
report(kind, start, res, id);
|
||||
}
|
||||
|
||||
// имя сценария — имя класса и экспортируемой функции (exec)
|
||||
export function upload() {
|
||||
postUpload("upload", GOOD_BODY);
|
||||
}
|
||||
|
||||
export function upload_bad() {
|
||||
postUpload("upload_bad", BAD_BODY);
|
||||
}
|
||||
|
||||
// регистрация — редкий медленный маршрут (Argon2id): имя из UUID без
|
||||
// дефисов (шаблон контракта ^[a-z0-9_]{3,32}$), пароль сразу выбрасывается
|
||||
export function register() {
|
||||
const name = `t${crypto.randomUUID().split("-").join("").slice(0, 30)}`;
|
||||
const start = Date.now();
|
||||
const res = http.post(
|
||||
`${API}/users`,
|
||||
JSON.stringify({
|
||||
username: name,
|
||||
display_name: "Bench telemetry",
|
||||
password: crypto.randomUUID(),
|
||||
}),
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
responseType: "none",
|
||||
timeout: TIMEOUT,
|
||||
responseCallback: http.expectedStatuses(201),
|
||||
},
|
||||
);
|
||||
report("register", start, res);
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
// t0 — в строке t-t0, итог без данных setup
|
||||
delete data.setup_data;
|
||||
return summaryFiles(data);
|
||||
}
|
||||
+31
-4
@@ -1,5 +1,6 @@
|
||||
"""Файлы классов профиля очереди (design change `track1-queue-overload`,
|
||||
решение 5): `s`, `m`, `lj`, `lp`, детерминированно от зерна.
|
||||
решение 5): `s`, `m`, `lj`, `lp`, детерминированно от зерна; класс `bad` —
|
||||
профиль цены телеметрии (design change `track1-telemetry-cost`, решение 8).
|
||||
|
||||
Только в контейнере `mtusi-bench-images` на образе стенда: Pillow образа и та же
|
||||
его версия, что у процесса обработки; `src` не импортируется. На stdout — JSON с
|
||||
@@ -15,7 +16,7 @@ import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageChops
|
||||
from PIL import Image, ImageChops, UnidentifiedImageError
|
||||
from uploads import png_noise
|
||||
|
||||
MAX_BYTES = 10_485_760
|
||||
@@ -29,6 +30,8 @@ FINE_DIVISOR = 6
|
||||
TILE = 512
|
||||
AMPLITUDE = 24
|
||||
POSTERIZE_MASK = 0xF0
|
||||
# точность в SOF, которую Pillow не декодирует
|
||||
PRECISION_12 = 12
|
||||
|
||||
|
||||
def noise_l(width: int, height: int, seed: int) -> Image.Image:
|
||||
@@ -125,11 +128,36 @@ def build_m(seed: int) -> bytes:
|
||||
return png_noise(NOISE_HEIGHT, seed + NOISE_HEIGHT)
|
||||
|
||||
|
||||
def build_bad(seed: int) -> bytes:
|
||||
"""Класс `bad` профиля цены телеметрии (design change
|
||||
`track1-telemetry-cost`, решение 8): байты `s` с 12 битами точности в
|
||||
SOF — структура верна (202), Pillow не декодирует (`failed`,
|
||||
`invalid_image`), как `images.jpeg_precision_12()` тестов."""
|
||||
data = bytearray(build_s(seed))
|
||||
sof = data.index(b"\xff\xc0")
|
||||
data[sof + 4] = PRECISION_12
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def image_size(data: bytes) -> tuple[int, int]:
|
||||
"""Ширина и высота: Pillow, а у `bad`, который Pillow не открывает, —
|
||||
поля SOF (высота и ширина после точности)."""
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
return image.size
|
||||
except UnidentifiedImageError:
|
||||
sof = data.index(b"\xff\xc0")
|
||||
height = int.from_bytes(data[sof + 5 : sof + 7], "big")
|
||||
width = int.from_bytes(data[sof + 7 : sof + 9], "big")
|
||||
return width, height
|
||||
|
||||
|
||||
BUILDERS = {
|
||||
"s": (build_s, "s.jpg", "image/jpeg"),
|
||||
"m": (build_m, "m.png", "image/png"),
|
||||
"lj": (build_lj, "lj.jpg", "image/jpeg"),
|
||||
"lp": (build_lp, "lp.png", "image/png"),
|
||||
"bad": (build_bad, "bad.jpg", "image/jpeg"),
|
||||
}
|
||||
|
||||
|
||||
@@ -139,8 +167,7 @@ def main() -> int:
|
||||
code = 0
|
||||
for name, (build, filename, media) in BUILDERS.items():
|
||||
data = build(seed)
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
width, height = image.size
|
||||
width, height = image_size(data)
|
||||
(directory / filename).write_bytes(data)
|
||||
report[name] = {
|
||||
"file": filename,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# bench-lean: begin
|
||||
# Конфигурация Prometheus вариантов `metrics` и `balanced` профиля цены
|
||||
# телеметрии (design change track1-telemetry-cost, решение 7): копия
|
||||
# infra/otel/prometheus/prometheus.yml плюс размеченные блоки отбора рядов у
|
||||
# целей loki, tempo и prometheus. Prometheus конфигурации не сливает, поэтому
|
||||
# копия; вне строк `bench-lean` файл обязан совпадать с рабочим построчно —
|
||||
# это проверяют run.py до стенда и `telemetry_cost.py --selftest`. Остаются
|
||||
# ряды приёма, отказов и объёма хранения (их же читает профиль) и `up`
|
||||
# (синтетический, отбор его не касается); ряды приложения и Collector — все.
|
||||
# Рабочий стенд забирает все ряды (решение 5).
|
||||
# bench-lean: end
|
||||
# Prometheus v3.15.1 — хранилище метрик (design change otel-telemetry,
|
||||
# решения 3 и 15). Метрики приложения — scrape экспортёра prometheus
|
||||
# Collector (honor_labels: job = service.name, instance = service.instance.id
|
||||
# из OTLP; там же метрики LB с job = haproxy), плюс собственные метрики
|
||||
# Collector, Loki, Tempo и самого Prometheus: по ним видно, жив ли конвейер.
|
||||
# Срок и предел объёма хранения, путь данных и время начала рядов — флаги
|
||||
# команды в docker-compose.yml. Приёмников remote write и OTLP, admin API и
|
||||
# lifecycle нет; порт не публикуется. Правила записи и оповещения — rules.yml
|
||||
# (design change slo-alerts, решения 1, 3, 4, 9); блока alerting нет:
|
||||
# доставки наружу нет, состояние firing / resolved — API правил, ряды ALERTS и
|
||||
# Grafana.
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
# явно прежний текстовый список Prometheus 3 по умолчанию: флаг
|
||||
# created-timestamp-zero-ingestion иначе переводит на protobuf все цели, а
|
||||
# время начала нужно только экспортёру Collector (решение 6)
|
||||
scrape_protocols:
|
||||
- OpenMetricsText1.0.0
|
||||
- OpenMetricsText0.0.1
|
||||
- PrometheusText1.0.0
|
||||
- PrometheusText0.0.4
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yml
|
||||
|
||||
scrape_configs:
|
||||
# метрики API, worker и relay, пришедшие в Collector по OTLP, и метрики LB
|
||||
# с приёмника prometheus/haproxy. Protobuf первым: время начала
|
||||
# cumulative-ряда экспортёр Collector отдаёт только в нём, и Prometheus
|
||||
# пишет ноль в момент старта нового процесса (решение 6)
|
||||
- job_name: otel-collector-exporter
|
||||
honor_labels: true
|
||||
scrape_protocols:
|
||||
- PrometheusProto
|
||||
- OpenMetricsText1.0.0
|
||||
- PrometheusText0.0.4
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
- job_name: otel-collector
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8888"]
|
||||
- job_name: loki
|
||||
static_configs:
|
||||
- targets: ["loki:3100"]
|
||||
# bench-lean: begin
|
||||
# приём (байты, строки, структурированные метаданные), объём чанков,
|
||||
# отказы записи и отброшенное
|
||||
metric_relabel_configs:
|
||||
- source_labels: [__name__]
|
||||
action: keep
|
||||
regex: loki_distributor_(bytes|lines|structured_metadata_bytes)_received_total|loki_ingester_chunk_stored_bytes_total|loki_ingester_(chunks_flush_failures|wal_disk_full_failures)_total|loki_discarded_.*
|
||||
# bench-lean: end
|
||||
- job_name: tempo
|
||||
static_configs:
|
||||
- targets: ["tempo:3200"]
|
||||
# bench-lean: begin
|
||||
# приём (байты, span), приём live-store, его отказы и отброшенные span
|
||||
metric_relabel_configs:
|
||||
- source_labels: [__name__]
|
||||
action: keep
|
||||
regex: tempo_distributor_(bytes|spans)_received_total|tempo_live_store_bytes_received_total|tempo_live_store_.*failed.*|tempo_discarded_spans_total
|
||||
# bench-lean: end
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["127.0.0.1:9090"]
|
||||
# bench-lean: begin
|
||||
# ряды и отсчёты головы, отказы правил, компакций и журнала предзаписи
|
||||
metric_relabel_configs:
|
||||
- source_labels: [__name__]
|
||||
action: keep
|
||||
regex: prometheus_tsdb_head_(series|samples_appended_total)|prometheus_rule_evaluation_failures_total|prometheus_tsdb_(compactions_failed|wal_corruptions)_total
|
||||
# bench-lean: end
|
||||
@@ -0,0 +1,59 @@
|
||||
# Слой Collector варианта `balanced` профиля цены телеметрии — предложенная
|
||||
# сбалансированная конфигурация (design change track1-telemetry-cost,
|
||||
# решение 5; спек observability, «Сбалансированная конфигурация телеметрии»).
|
||||
# SDK отправляет все трассы, решение — после завершения трассы, по правилам
|
||||
# этой системы; журнал и метрики не выбираются. Вместе с ним —
|
||||
# bench/otel/prometheus-lean.yml. Рабочий стенд остаётся со всеми трассами.
|
||||
#
|
||||
# Запуск — вторым `--config` после infra/otel/collector.yaml; слой меняет
|
||||
# только процессор выбора трасс и список процессоров pipeline трасс
|
||||
# (проверка run.py до стенда, решение 6). Если метка не подтвердит B1–B3,
|
||||
# правило правки — design, решение 12: один параметр на нарушение.
|
||||
processors:
|
||||
tail_sampling:
|
||||
# цепочка загрузки ниже насыщения — до ~3 с (relay раз в 0,25 с,
|
||||
# обработка 0,3–1 с, пакет SDK 1 с): запас втрое; память Collector
|
||||
# пропорциональна сроку
|
||||
decision_wait: 10s
|
||||
# ~250 трасс/с × 10 с = 2500: восьмикратный запас без роста карт
|
||||
num_traces: 20000
|
||||
expected_new_traces_per_sec: 300
|
||||
# поздние span сохранённой трассы (повтор, replay) остаются с ней;
|
||||
# поздние span несохранённой — заново через правила: ошибка worker после
|
||||
# решения по API сохраняется хотя бы частичной трассой
|
||||
decision_cache:
|
||||
sampled_cache_size: 100000
|
||||
non_sampled_cache_size: 0
|
||||
policies:
|
||||
# 5xx API, исключения, отказ хранилища в span
|
||||
- name: errors
|
||||
type: status_code
|
||||
status_code:
|
||||
status_codes: [ERROR]
|
||||
# неуспешный исход задания: у `failed` нет статуса ошибки span (исход, а
|
||||
# не исключение, otel-telemetry OT-11)
|
||||
- name: job-outcome
|
||||
type: string_attribute
|
||||
string_attribute:
|
||||
key: messenger.job.outcome
|
||||
values: [failed, retry, error, requeued, dropped]
|
||||
# порог SLO на запрос, а не на трассу: длительность трассы загрузки
|
||||
# больше 0,25 с у каждой загрузки; 5 с — больше пути обработки без
|
||||
# повторов (0,3–1 с)
|
||||
- name: slow-spans
|
||||
type: ottl_condition
|
||||
ottl_condition:
|
||||
error_mode: ignore
|
||||
span:
|
||||
- kind == SPAN_KIND_SERVER and end_time_unix_nano - start_time_unix_nano >= 250000000
|
||||
- kind == SPAN_KIND_CONSUMER and end_time_unix_nano - start_time_unix_nano >= 5000000000
|
||||
# остальные трассы — как вариант `head`
|
||||
- name: rest
|
||||
type: probabilistic
|
||||
probabilistic:
|
||||
sampling_percentage: 10
|
||||
|
||||
service:
|
||||
pipelines:
|
||||
traces:
|
||||
processors: [memory_limiter, tail_sampling, batch]
|
||||
@@ -0,0 +1,33 @@
|
||||
# Слой Collector варианта `tail` профиля цены телеметрии (design change
|
||||
# track1-telemetry-cost, решения 2 и 6): типовой tail sampling, каким его
|
||||
# включают по документации, — трассы со span в статусе ошибки, трассы не
|
||||
# короче 0,25 с (граница SLO задержки, slo-alerts SA-1) и 10 % остальных.
|
||||
# Остальное по умолчанию: decision_wait 30 с, num_traces 50 000, кэшей решений
|
||||
# нет. Только для стенда bench/: рабочий стенд — со всеми трассами (решение 5).
|
||||
#
|
||||
# Запуск — вторым `--config` после infra/otel/collector.yaml: карты сливаются,
|
||||
# списки заменяются. Слой меняет только процессор выбора трасс и список
|
||||
# процессоров pipeline трасс; это проверяет run.py до стенда (validate и
|
||||
# сравнение print-config со слоем и без него, решение 6).
|
||||
processors:
|
||||
tail_sampling:
|
||||
policies:
|
||||
- name: errors
|
||||
type: status_code
|
||||
status_code:
|
||||
status_codes: [ERROR]
|
||||
# длительность трассы целиком: у асинхронной цепочки загрузки
|
||||
# (API → relay → worker) она больше 0,25 с всегда
|
||||
- name: slow-traces
|
||||
type: latency
|
||||
latency:
|
||||
threshold_ms: 250
|
||||
- name: rest
|
||||
type: probabilistic
|
||||
probabilistic:
|
||||
sampling_percentage: 10
|
||||
|
||||
service:
|
||||
pipelines:
|
||||
traces:
|
||||
processors: [memory_limiter, tail_sampling, batch]
|
||||
@@ -33,6 +33,9 @@ ROLES = (
|
||||
"cleaner",
|
||||
"haproxy",
|
||||
)
|
||||
# сервисы телеметрии стенда при выключателе TELEMETRY=on (design change
|
||||
# track1-telemetry-cost, решение 13)
|
||||
TELEMETRY_ROLES = ("otel-collector", "prometheus", "loki", "tempo")
|
||||
# условие H6, записанное до метки: состав не меняется
|
||||
H6_FLAGS = ("lost", "stuck", "duplicate", "sha_mismatch")
|
||||
# пометки, при которых метка не зелёная: система потеряла работу (решение 11) или
|
||||
@@ -177,6 +180,14 @@ CELL_FIELDS = [
|
||||
"worker_exit_codes",
|
||||
"worker_oom_events",
|
||||
"lb_up_min",
|
||||
# выключатель телеметрии (design change track1-telemetry-cost, решение
|
||||
# 13): CPU и троттлинг окна over и пик памяти сервисов телеметрии; без
|
||||
# телеметрии — пусто
|
||||
*[
|
||||
f"tel_{role.replace('-', '_')}_{key}"
|
||||
for role in TELEMETRY_ROLES
|
||||
for key in ("cpu_over", "throttle_over", "peak_mib")
|
||||
],
|
||||
]
|
||||
TIMELINE_FIELDS = [
|
||||
"cell",
|
||||
@@ -983,6 +994,20 @@ def cell_row(cell: Mapping[str, Any], src: Sources) -> dict[str, Any]:
|
||||
sum(1 for i in both_ready if done_at(i) > recovery_end),
|
||||
)
|
||||
row.update(control_columns(src.control, bounds))
|
||||
for role in TELEMETRY_ROLES:
|
||||
lives = src.cg.get(role, [])
|
||||
prefix = f"tel_{role.replace('-', '_')}"
|
||||
flat = [life for each in lives for life in each]
|
||||
peaks = [p[1] for each in src.mp.get(role, []) for p in each]
|
||||
row[f"{prefix}_cpu_over"] = (
|
||||
role_cores(lives, over_start, over_end) if lives else None
|
||||
)
|
||||
row[f"{prefix}_throttle_over"] = (
|
||||
throttle_share(flat, over_start, over_end) if flat else None
|
||||
)
|
||||
row[f"{prefix}_peak_mib"] = (
|
||||
round(max(peaks) / 2**20, 1) if peaks else None
|
||||
)
|
||||
row["flags"] = " ".join(
|
||||
cell_flags(row, zero_at is None, src.storage_down),
|
||||
)
|
||||
@@ -1854,6 +1879,29 @@ def block_table(rows: list[Mapping[str, Any]]) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def telemetry_line(meta: Mapping[str, Any]) -> str:
|
||||
"""Режим телеметрии метки (design change `track1-telemetry-cost`, решение
|
||||
13) и предупреждение о сумме лимитов CPU больше ВМ."""
|
||||
mode = meta.get("profile", {}).get("telemetry") or "off"
|
||||
if mode != "on":
|
||||
return (
|
||||
"Телеметрия стенда выключена (TELEMETRY=off): SDK реплик, worker и "
|
||||
"relay выключен, сервисов телеметрии нет."
|
||||
)
|
||||
budget = meta.get("resources", {}).get("budget", {})
|
||||
text = (
|
||||
"Телеметрия стенда включена (TELEMETRY=on): SDK реплик, worker и relay "
|
||||
"с настройками рабочего стенда, Collector, Prometheus, Loki и Tempo "
|
||||
"рабочего стенда; столбцы `tel_*` в конце `cells.csv`."
|
||||
)
|
||||
if budget.get("cpus", 0) > budget.get("vm_cpus", 0) > 0:
|
||||
text += (
|
||||
f" Сумма лимитов CPU {budget['cpus']:g} больше CPU ВМ "
|
||||
f"{budget['vm_cpus']}: лимиты делят время, а не резервируют ядра."
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
def render_summary(
|
||||
meta: Mapping[str, Any],
|
||||
rows: list[Mapping[str, Any]],
|
||||
@@ -1868,6 +1916,8 @@ def render_summary(
|
||||
f"dirty {meta.get('git', {}).get('dirty')}, статус "
|
||||
f"{meta.get('status')}, ячеек {len(rows)} из {plan_total}.",
|
||||
"",
|
||||
telemetry_line(meta),
|
||||
"",
|
||||
]
|
||||
fatal = [
|
||||
f"`{row['cell']}`: {row['flags']}"
|
||||
|
||||
+1206
-27
File diff suppressed because it is too large
Load Diff
+10
-2
@@ -42,6 +42,11 @@
|
||||
# `mq <нс> missing`). В фоне psql с \watch пишет /work/jobs.log (одно
|
||||
# соединение): jobs|<мс>|outbox|waiting|published|processing|oldest_s|
|
||||
# staging_ready. Разбор — bench/overload.py.
|
||||
# cost (профиль цены телеметрии, design change track1-telemetry-cost,
|
||||
# решение 10): <интервал, с> cost
|
||||
# Контейнер без сети, как scan: строки `cg` всех контейнеров ВМ, `vm` и
|
||||
# `mp` каждого контейнера (memory.peak, anon, oom_kill), как у queue. Ни
|
||||
# psql, ни опроса LB и брокера. Разбор — bench/telemetry_cost.py.
|
||||
set -u
|
||||
|
||||
interval=$1
|
||||
@@ -50,6 +55,9 @@ mode=list
|
||||
if [[ ${1:-} == scan ]]; then
|
||||
mode=scan
|
||||
shift
|
||||
elif [[ ${1:-} == cost ]]; then
|
||||
mode=cost
|
||||
shift
|
||||
elif [[ ${1:-} == queue ]]; then
|
||||
mode=queue
|
||||
queue_name=$2
|
||||
@@ -290,13 +298,13 @@ hex64='^[0-9a-f]{64}$'
|
||||
while :; do
|
||||
# EPOCHREALTIME bash 5 — часы ВМ без запуска date
|
||||
ns=${EPOCHREALTIME/./}000
|
||||
if [[ $mode == scan || $mode == queue ]]; then
|
||||
if [[ $mode == scan || $mode == queue || $mode == cost ]]; then
|
||||
for dir in /sys/fs/cgroup/docker/*/; do
|
||||
dir=${dir%/}
|
||||
id=${dir##*/}
|
||||
if [[ $id =~ $hex64 ]]; then
|
||||
cg_line - "$id"
|
||||
[[ $mode == queue ]] && mp_line "$id"
|
||||
[[ $mode == queue || $mode == cost ]] && mp_line "$id"
|
||||
fi
|
||||
done
|
||||
else
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Override включённой телеметрии стенда bench/ (design change
|
||||
# track1-telemetry-cost, решения 1 и 13): второй -f после bench.compose.yml —
|
||||
# у вариантов профиля цены телеметрии с телеметрией и у профилей загрузок и
|
||||
# очереди с TELEMETRY=on. SDK реплик, worker и relay включён и отправляет в
|
||||
# Collector стенда; доля выбора трасс, набор границ и интервал — значения по
|
||||
# умолчанию (рабочий стенд), вариант профиля задаёт их своим override
|
||||
# (.work/variant.compose.yml). Без этого файла телеметрия стенда выключена
|
||||
# (TELEMETRY__ENABLED: "false" в bench.compose.yml)
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
TELEMETRY__ENABLED: "true"
|
||||
TELEMETRY__OTLP_ENDPOINT: http://otel-collector:4318
|
||||
|
||||
worker:
|
||||
environment:
|
||||
TELEMETRY__ENABLED: "true"
|
||||
TELEMETRY__OTLP_ENDPOINT: http://otel-collector:4318
|
||||
|
||||
relay:
|
||||
environment:
|
||||
TELEMETRY__ENABLED: "true"
|
||||
TELEMETRY__OTLP_ENDPOINT: http://otel-collector:4318
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,625 @@
|
||||
"""Выборка из хранилищ телеметрии профиля цены телеметрии.
|
||||
|
||||
Design change `track1-telemetry-cost`, решение 9. Только в контейнере
|
||||
`mtusi-bench-lookup` на образе стенда, в сети хранилищ `mtusi-bench-telemetry`;
|
||||
только stdlib (`urllib`), `src` не импортирует, `bench/` — на чтение. Запросы
|
||||
— HTTP API Tempo, Loki, Prometheus и метрики Collector, пулом из восьми
|
||||
потоков.
|
||||
|
||||
python telemetry_lookup.py wait-ready [--timeout 90]
|
||||
python telemetry_lookup.py collect <события.json> <итог.json>
|
||||
|
||||
`wait-ready` — `/-/ready` Prometheus, `/ready` Loki и Tempo, `:8888/metrics`
|
||||
Collector; код 0 — все готовы, 1 — срок вышел. `collect` — по событиям прогона
|
||||
(id запросов редких классов, выборка нормальных, окна) ищет трассы по
|
||||
`span.messenger.request_id` (и цельные цепочки загрузок), записи журнала по
|
||||
`request_id` и их переход к трассе, счётчики Prometheus (приём, потери,
|
||||
события), ряды по `job`, `status/tsdb`, признаки слоёв Collector и
|
||||
Prometheus, квантили из buckets против журнала. Результат поиска, равный
|
||||
пределу числа результатов, — отказ «lookup truncated» (код 1): неполный счёт
|
||||
не выдаётся за полный.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
PROMETHEUS = "http://prometheus:9090"
|
||||
LOKI = "http://loki:3100"
|
||||
TEMPO = "http://tempo:3200"
|
||||
COLLECTOR = "http://otel-collector:8888"
|
||||
READY = (
|
||||
f"{PROMETHEUS}/-/ready",
|
||||
f"{LOKI}/ready",
|
||||
f"{TEMPO}/ready",
|
||||
f"{COLLECTOR}/metrics",
|
||||
)
|
||||
THREADS = 8
|
||||
# переходы журнал → трасса: потоков на класс (классы идут параллельно)
|
||||
LINK_THREADS = 2
|
||||
TIMEOUT_S = 60
|
||||
ATTEMPTS = 4
|
||||
RETRY_PAUSE_S = 1.0
|
||||
# счётчики по краям окна: шаг — интервал scrape, взгляд назад — был ли ряд
|
||||
# до окна
|
||||
STEP_S = 15
|
||||
LOOKBACK_S = 60
|
||||
# id в одном поиске Tempo и Loki: регулярное выражение в query string
|
||||
BATCH = 40
|
||||
# предел результатов — не меньше 4 × ожидаемого (решение 9)
|
||||
LIMIT_FACTOR = 4
|
||||
API_SERVICE = "messenger-api"
|
||||
REQUEST_ATTR = "span.messenger.request_id"
|
||||
# у загрузки цепочка — server span API, span producer relay, consumer span
|
||||
# worker с итогом задания
|
||||
CHAIN_OUTCOME = {"upload": "ready", "upload_bad": "failed"}
|
||||
# имена Collector — без суффикса _total у собственных метрик (rule
|
||||
# telemetry.md); на всякий случай оба варианта
|
||||
TOTALS = {
|
||||
"sdk_span_started_sampled": (
|
||||
'sum(otel_sdk_span_started_total{otel_span_sampling_result='
|
||||
'"RECORD_AND_SAMPLE"})'
|
||||
),
|
||||
"sdk_span_started_dropped": (
|
||||
'sum(otel_sdk_span_started_total{otel_span_sampling_result="DROP"})'
|
||||
),
|
||||
"sdk_span_processed_ok": (
|
||||
'sum(otel_sdk_processor_span_processed_total{error_type=""})'
|
||||
),
|
||||
"sdk_span_processed_lost": (
|
||||
'sum(otel_sdk_processor_span_processed_total{error_type!=""})'
|
||||
),
|
||||
"sdk_span_exported_ok": (
|
||||
'sum(otel_sdk_exporter_span_exported_total{error_type=""})'
|
||||
),
|
||||
"sdk_span_export_failed": (
|
||||
'sum(otel_sdk_exporter_span_exported_total{error_type!=""})'
|
||||
),
|
||||
"sdk_log_processed_ok": (
|
||||
'sum(otel_sdk_processor_log_processed_total{error_type=""})'
|
||||
),
|
||||
"sdk_log_processed_lost": (
|
||||
'sum(otel_sdk_processor_log_processed_total{error_type!=""})'
|
||||
),
|
||||
"sdk_log_exported_ok": (
|
||||
'sum(otel_sdk_exporter_log_exported_total{error_type=""})'
|
||||
),
|
||||
"sdk_log_export_failed": (
|
||||
'sum(otel_sdk_exporter_log_exported_total{error_type!=""})'
|
||||
),
|
||||
"col_accepted_spans": "otelcol_receiver_accepted_spans",
|
||||
"col_refused_spans": "otelcol_receiver_refused_spans",
|
||||
"col_failed_spans": "otelcol_receiver_failed_spans",
|
||||
"col_accepted_logs": "otelcol_receiver_accepted_log_records",
|
||||
"col_refused_logs": "otelcol_receiver_refused_log_records",
|
||||
"col_failed_logs": "otelcol_receiver_failed_log_records",
|
||||
"col_accepted_points": "otelcol_receiver_accepted_metric_points",
|
||||
"col_refused_points": "otelcol_receiver_refused_metric_points",
|
||||
"col_sent_spans": "otelcol_exporter_sent_spans",
|
||||
"col_send_failed_spans": "otelcol_exporter_send_failed_spans",
|
||||
"col_enqueue_failed_spans": "otelcol_exporter_enqueue_failed_spans",
|
||||
"col_sent_logs": "otelcol_exporter_sent_log_records",
|
||||
"col_send_failed_logs": "otelcol_exporter_send_failed_log_records",
|
||||
"col_enqueue_failed_logs": "otelcol_exporter_enqueue_failed_log_records",
|
||||
"col_sent_points": "otelcol_exporter_sent_metric_points",
|
||||
"tail_sampled": (
|
||||
"otelcol_processor_tail_sampling_global_count_traces_sampled"
|
||||
'{sampled="true"}'
|
||||
),
|
||||
"tail_not_sampled": (
|
||||
"otelcol_processor_tail_sampling_global_count_traces_sampled"
|
||||
'{sampled="false"}'
|
||||
),
|
||||
"tail_dropped_too_early": (
|
||||
"otelcol_processor_tail_sampling_sampling_trace_dropped_too_early"
|
||||
),
|
||||
"tail_new_traces": (
|
||||
"otelcol_processor_tail_sampling_new_trace_id_received"
|
||||
),
|
||||
"tail_policy_errors": (
|
||||
"otelcol_processor_tail_sampling_sampling_policy_evaluation_error"
|
||||
),
|
||||
"tempo_spans": "sum(tempo_distributor_spans_received_total)",
|
||||
"tempo_bytes": "sum(tempo_distributor_bytes_received_total)",
|
||||
"loki_lines": "sum(loki_distributor_lines_received_total)",
|
||||
"loki_bytes": "sum(loki_distributor_bytes_received_total)",
|
||||
"loki_sm_bytes": (
|
||||
"sum(loki_distributor_structured_metadata_bytes_received_total)"
|
||||
),
|
||||
"prom_series": "max(prometheus_tsdb_head_series)",
|
||||
"prom_samples": "sum(prometheus_tsdb_head_samples_appended_total)",
|
||||
}
|
||||
# счётчики, приращение которых нужно за чистое окно (приём, решение 9)
|
||||
CLEAN = (
|
||||
"col_accepted_spans",
|
||||
"col_accepted_logs",
|
||||
"col_accepted_points",
|
||||
"tempo_spans",
|
||||
"tempo_bytes",
|
||||
"loki_lines",
|
||||
"loki_bytes",
|
||||
"loki_sm_bytes",
|
||||
"prom_samples",
|
||||
"prom_series",
|
||||
)
|
||||
GAUGES = frozenset({"prom_series"})
|
||||
CONTENT_ROUTE = "/api/v1/attachments/{attachment_id}/content"
|
||||
MESSAGES_ROUTE = "/api/v1/chats/{chat_id}/messages"
|
||||
HTTP_COUNT = "http_server_request_duration_seconds_count"
|
||||
HTTP_BUCKET = "http_server_request_duration_seconds_bucket"
|
||||
RARE_METRICS = {
|
||||
"broken": (
|
||||
f'sum({HTTP_COUNT}{{http_route="{CONTENT_ROUTE}",'
|
||||
'http_response_status_code="500"})'
|
||||
),
|
||||
"register": (
|
||||
f'sum({HTTP_COUNT}{{http_route="/api/v1/users",'
|
||||
'http_request_method="POST",http_response_status_code="201"})'
|
||||
),
|
||||
"write_slow": (
|
||||
f'sum({HTTP_COUNT}{{http_route="{MESSAGES_ROUTE}",'
|
||||
'http_request_method="POST"}) - '
|
||||
f'sum({HTTP_BUCKET}{{http_route="{MESSAGES_ROUTE}",'
|
||||
'http_request_method="POST",le="0.25"})'
|
||||
),
|
||||
"upload_bad": (
|
||||
'sum(messenger_job_duration_seconds_count{messenger_job_outcome='
|
||||
'"failed"})'
|
||||
),
|
||||
"upload": "sum(messenger_job_time_to_ready_seconds_count)",
|
||||
}
|
||||
QUANTILES = (0.95, 0.99)
|
||||
|
||||
|
||||
class TruncatedError(Exception):
|
||||
"""Поиск упёрся в предел числа результатов."""
|
||||
|
||||
|
||||
def collector_name(expr: str) -> str:
|
||||
"""Имя Collector с и без `_total`: `sum({__name__=~"имя(_total)?", …})`."""
|
||||
if expr.startswith(("sum(", "max(")):
|
||||
return expr
|
||||
name, _, labels = expr.partition("{")
|
||||
labels = labels.rstrip("}")
|
||||
matcher = f'__name__=~"{name}(_total)?"'
|
||||
if labels:
|
||||
matcher += f",{labels}"
|
||||
return f"sum({{{matcher}}})"
|
||||
|
||||
|
||||
def fetch(url: str) -> bytes:
|
||||
"""GET с повтором на обрыв соединения и 5xx: хранилище с 0,5 CPU под
|
||||
пулом запросов изредка закрывает соединение без ответа. 4xx — сразу."""
|
||||
for attempt in range(1, ATTEMPTS + 1):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=TIMEOUT_S) as response:
|
||||
return response.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code < 500 or attempt == ATTEMPTS:
|
||||
raise
|
||||
except (OSError, urllib.error.URLError):
|
||||
if attempt == ATTEMPTS:
|
||||
raise
|
||||
time.sleep(RETRY_PAUSE_S * attempt)
|
||||
raise AssertionError("unreachable")
|
||||
|
||||
|
||||
def get(url: str, params: dict[str, Any] | None = None) -> Any:
|
||||
if params:
|
||||
url = f"{url}?{urllib.parse.urlencode(params)}"
|
||||
body = fetch(url)
|
||||
return json.loads(body) if body[:1] in (b"{", b"[") else body
|
||||
|
||||
|
||||
def exists(url: str) -> bool:
|
||||
try:
|
||||
fetch(url)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def wait_ready(timeout: float) -> int:
|
||||
deadline = time.monotonic() + timeout
|
||||
pending = list(READY)
|
||||
while time.monotonic() < deadline:
|
||||
left = []
|
||||
for url in pending:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as response:
|
||||
response.read()
|
||||
if response.status != 200:
|
||||
left.append(url)
|
||||
except (OSError, urllib.error.URLError):
|
||||
left.append(url)
|
||||
pending = left
|
||||
if not pending:
|
||||
print("telemetry storages ready", flush=True)
|
||||
return 0
|
||||
time.sleep(1)
|
||||
print(f"not ready in {timeout:.0f}s: {pending}", flush=True)
|
||||
return 1
|
||||
|
||||
|
||||
def batches(items: list[str]) -> list[list[str]]:
|
||||
return [items[i : i + BATCH] for i in range(0, len(items), BATCH)]
|
||||
|
||||
|
||||
def tempo_search(query: str, window: dict[str, float], expected: int) -> Any:
|
||||
limit = max(20, LIMIT_FACTOR * expected)
|
||||
data = get(
|
||||
f"{TEMPO}/api/search",
|
||||
{
|
||||
"q": query,
|
||||
"start": int(window["start"]),
|
||||
"end": int(window["end"]) + 1,
|
||||
"limit": limit,
|
||||
"spss": 10,
|
||||
},
|
||||
)
|
||||
traces = data.get("traces") or []
|
||||
if len(traces) >= limit:
|
||||
raise TruncatedError(
|
||||
f"lookup truncated: tempo {len(traces)} = {limit}",
|
||||
)
|
||||
return traces
|
||||
|
||||
|
||||
def request_ids_in(traces: list[dict[str, Any]]) -> set[str]:
|
||||
found = set()
|
||||
for item in traces:
|
||||
for spanset in item.get("spanSets") or [item.get("spanSet") or {}]:
|
||||
for span in spanset.get("spans") or []:
|
||||
for attr in span.get("attributes") or []:
|
||||
if attr.get("key") == "messenger.request_id":
|
||||
found.add(attr["value"].get("stringValue", ""))
|
||||
return found
|
||||
|
||||
|
||||
def traces_of(
|
||||
ids: list[str],
|
||||
window: dict[str, float],
|
||||
outcome: str | None = None,
|
||||
) -> set[str]:
|
||||
"""Id запросов, у которых в Tempo есть трасса (у `outcome` — цельная
|
||||
цепочка загрузки с consumer span этого итога и span producer)."""
|
||||
found: set[str] = set()
|
||||
for part in batches(ids):
|
||||
pattern = "|".join(part)
|
||||
query = f'{{ {REQUEST_ATTR} =~ "{pattern}" }}'
|
||||
if outcome is not None:
|
||||
query += (
|
||||
" && { kind = consumer && span.messenger.job.outcome = "
|
||||
f'"{outcome}" }} && {{ kind = producer }}'
|
||||
)
|
||||
query += f" | select({REQUEST_ATTR})"
|
||||
found |= request_ids_in(tempo_search(query, window, len(part)))
|
||||
return found & set(ids)
|
||||
|
||||
|
||||
def loki_records(
|
||||
ids: list[str],
|
||||
window: dict[str, float],
|
||||
) -> dict[str, dict[str, str]]:
|
||||
"""Запись доступа API по `request_id`: метки потока (поля записи)."""
|
||||
out: dict[str, dict[str, str]] = {}
|
||||
for part in batches(ids):
|
||||
limit = LIMIT_FACTOR * len(part) + 10
|
||||
query = (
|
||||
f'{{service_name="{API_SERVICE}"}} | middleware="http" | '
|
||||
f'request_id=~"{"|".join(part)}"'
|
||||
)
|
||||
data = get(
|
||||
f"{LOKI}/loki/api/v1/query_range",
|
||||
{
|
||||
"query": query,
|
||||
"start": int(window["start"] * 1e9),
|
||||
"end": int((window["end"] + 1) * 1e9),
|
||||
"limit": limit,
|
||||
"direction": "forward",
|
||||
},
|
||||
)
|
||||
streams = data["data"]["result"]
|
||||
lines = sum(len(stream["values"]) for stream in streams)
|
||||
if lines >= limit:
|
||||
raise TruncatedError(f"lookup truncated: loki {lines} = {limit}")
|
||||
for stream in streams:
|
||||
labels = stream["stream"]
|
||||
out[labels.get("request_id", "")] = labels
|
||||
return {key: value for key, value in out.items() if key in set(ids)}
|
||||
|
||||
|
||||
def trace_exists(trace_id: str) -> bool:
|
||||
"""Трасса есть и в ней есть span: на неизвестный id Tempo может ответить
|
||||
и пустым телом (пробный прогон `head` — 12 «найденных» трасс из 12
|
||||
невыбранных)."""
|
||||
try:
|
||||
body = fetch(f"{TEMPO}/api/v2/traces/{trace_id}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return False
|
||||
raise
|
||||
if not body.strip():
|
||||
return False
|
||||
data = json.loads(body)
|
||||
trace = data.get("trace", data)
|
||||
return bool(trace.get("resourceSpans") or trace.get("batches"))
|
||||
|
||||
|
||||
def class_result(
|
||||
name: str,
|
||||
ids: list[str],
|
||||
window: dict[str, float],
|
||||
slow_ms: float,
|
||||
) -> dict[str, Any]:
|
||||
traced = traces_of(ids, window)
|
||||
chains = None
|
||||
if name in CHAIN_OUTCOME and ids:
|
||||
chains = len(traces_of(ids, window, CHAIN_OUTCOME[name]))
|
||||
records = loki_records(ids, window) if ids else {}
|
||||
with_trace = {
|
||||
rid: labels["trace_id"]
|
||||
for rid, labels in records.items()
|
||||
if labels.get("trace_id")
|
||||
}
|
||||
sampled = sum(
|
||||
1
|
||||
for labels in records.values()
|
||||
if labels.get("flags", "").isdigit() and int(labels["flags"]) & 1
|
||||
)
|
||||
# свой пул: задачи классов уже заняли потоки общего
|
||||
with ThreadPoolExecutor(LINK_THREADS) as links:
|
||||
linked_by = dict(
|
||||
zip(
|
||||
with_trace,
|
||||
links.map(trace_exists, with_trace.values()),
|
||||
strict=True,
|
||||
),
|
||||
)
|
||||
linked = sum(linked_by.values())
|
||||
# медленные по серверу: длительность записи доступа (та же величина, что
|
||||
# server span) не меньше порога; по ней решает правило выбора трасс
|
||||
server_slow = {
|
||||
rid
|
||||
for rid, labels in records.items()
|
||||
if float(labels.get("duration_ms") or 0) >= slow_ms
|
||||
}
|
||||
return {
|
||||
"ids": len(ids),
|
||||
"traces": len(traced),
|
||||
"server_slow": len(server_slow),
|
||||
"server_slow_traces": len(server_slow & traced),
|
||||
"server_slow_linked": sum(
|
||||
1 for rid in server_slow if linked_by.get(rid)
|
||||
),
|
||||
"chains": chains,
|
||||
"logs": len(records),
|
||||
"logs_with_trace": len(with_trace),
|
||||
"logs_sampled_flag": sampled,
|
||||
"log_to_trace": linked,
|
||||
"missing_traces": sorted(set(ids) - traced)[:5],
|
||||
}
|
||||
|
||||
|
||||
def prom_value(expr: str, at: float) -> float | None:
|
||||
data = get(f"{PROMETHEUS}/api/v1/query", {"query": expr, "time": at})
|
||||
result = data["data"]["result"]
|
||||
if not result:
|
||||
return None
|
||||
value = float(result[0]["value"][1])
|
||||
# histogram_quantile без отсчётов — NaN: в JSON это не число
|
||||
return None if math.isnan(value) else value
|
||||
|
||||
|
||||
def prom_delta(
|
||||
expr: str,
|
||||
start: float,
|
||||
end: float,
|
||||
*,
|
||||
gauge: bool,
|
||||
) -> dict[str, float | None]:
|
||||
"""Разность первого отсчёта не раньше начала окна и последнего не позже
|
||||
конца (шаг 15 с, решение 9); у gauge — последнее значение."""
|
||||
data = get(
|
||||
f"{PROMETHEUS}/api/v1/query_range",
|
||||
{
|
||||
"query": expr,
|
||||
"start": start - LOOKBACK_S,
|
||||
"end": end,
|
||||
"step": STEP_S,
|
||||
},
|
||||
)
|
||||
result = data["data"]["result"]
|
||||
if not result:
|
||||
return {"delta": None, "seconds": None, "last": None}
|
||||
series = [(float(t), float(v)) for t, v in result[0]["values"]]
|
||||
inside = [(t, v) for t, v in series if start <= t <= end]
|
||||
if not inside:
|
||||
return {"delta": None, "seconds": None, "last": None}
|
||||
t1, v1 = inside[-1]
|
||||
if gauge:
|
||||
return {"delta": None, "seconds": t1 - inside[0][0], "last": v1}
|
||||
# ряд счётчика, которого до окна не было (Tempo заводит его на первый
|
||||
# принятый span — у tail через срок решения), начинается с нуля: база —
|
||||
# ноль в начале окна, а не первый отсчёт внутри (иначе приёма «нет»)
|
||||
if any(t < start for t, _ in series) and len(inside) >= 2:
|
||||
t0, v0 = inside[0]
|
||||
else:
|
||||
t0, v0 = start, 0.0
|
||||
if t1 <= t0:
|
||||
return {"delta": None, "seconds": None, "last": v1}
|
||||
return {"delta": v1 - v0, "seconds": t1 - t0, "last": v1}
|
||||
|
||||
|
||||
def quantiles(
|
||||
method: str,
|
||||
route: str,
|
||||
window: dict[str, float],
|
||||
) -> dict[str, float | None]:
|
||||
seconds = max(1, int(window["end"] - window["start"]))
|
||||
out: dict[str, float | None] = {}
|
||||
for q in QUANTILES:
|
||||
key = f"p{int(q * 100)}"
|
||||
out[f"{key}_buckets"] = prom_value(
|
||||
f"histogram_quantile({q}, sum by (le) (increase({HTTP_BUCKET}"
|
||||
f'{{http_route="{route}",http_request_method="{method}"}}'
|
||||
f"[{seconds}s])))",
|
||||
window["end"],
|
||||
)
|
||||
data = get(
|
||||
f"{LOKI}/loki/api/v1/query",
|
||||
{
|
||||
"query": (
|
||||
f"quantile_over_time({q}, "
|
||||
f'{{service_name="{API_SERVICE}"}} | middleware="http" '
|
||||
f'| method="{method}" | path="{route}" '
|
||||
f"| unwrap duration_ms [{seconds}s]) by ()"
|
||||
),
|
||||
"time": int(window["end"] * 1e9),
|
||||
},
|
||||
)
|
||||
result = data["data"]["result"]
|
||||
value = float(result[0]["value"][1]) / 1000 if result else None
|
||||
out[f"{key}_log"] = (
|
||||
None if value is None or math.isnan(value) else value
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def loki_counts(window: dict[str, float]) -> dict[str, int]:
|
||||
seconds = max(1, int(window["end"] - window["start"]))
|
||||
data = get(
|
||||
f"{LOKI}/loki/api/v1/query",
|
||||
{
|
||||
"query": (
|
||||
"sum by (method, path) (count_over_time("
|
||||
f'{{service_name="{API_SERVICE}"}} | middleware="http" '
|
||||
f"[{seconds}s]))"
|
||||
),
|
||||
"time": int(window["end"] * 1e9),
|
||||
},
|
||||
)
|
||||
return {
|
||||
f"{item['metric'].get('method', '')} {item['metric'].get('path', '')}": (
|
||||
int(float(item["value"][1]))
|
||||
)
|
||||
for item in data["data"]["result"]
|
||||
}
|
||||
|
||||
|
||||
def collect(events: dict[str, Any]) -> dict[str, Any]:
|
||||
started = time.monotonic()
|
||||
search = events["search"]
|
||||
run = events["run"]
|
||||
clean = events["clean"]
|
||||
out: dict[str, Any] = {"classes": {}}
|
||||
with ThreadPoolExecutor(THREADS) as pool:
|
||||
futures = {
|
||||
name: pool.submit(
|
||||
class_result,
|
||||
name,
|
||||
ids,
|
||||
search,
|
||||
float(events.get("slow_ms", 250)),
|
||||
)
|
||||
for name, ids in events["classes"].items()
|
||||
}
|
||||
sample = events.get("sample_me") or []
|
||||
sample_future = pool.submit(traces_of, sample, search)
|
||||
for name, future in futures.items():
|
||||
out["classes"][name] = future.result()
|
||||
out["sample_me"] = {
|
||||
"ids": len(sample),
|
||||
"traces": len(sample_future.result()),
|
||||
}
|
||||
at = search["end"]
|
||||
names = list(TOTALS)
|
||||
values = pool.map(
|
||||
lambda key: prom_value(collector_name(TOTALS[key]), at),
|
||||
names,
|
||||
)
|
||||
out["totals"] = dict(zip(names, values, strict=True))
|
||||
rare = list(RARE_METRICS)
|
||||
out["rare_metrics"] = dict(
|
||||
zip(
|
||||
rare,
|
||||
pool.map(lambda key: prom_value(RARE_METRICS[key], at), rare),
|
||||
strict=True,
|
||||
),
|
||||
)
|
||||
out["clean"] = dict(
|
||||
zip(
|
||||
CLEAN,
|
||||
pool.map(
|
||||
lambda key: prom_delta(
|
||||
collector_name(TOTALS[key]),
|
||||
clean["start"],
|
||||
clean["end"],
|
||||
gauge=key in GAUGES,
|
||||
),
|
||||
CLEAN,
|
||||
),
|
||||
strict=True,
|
||||
),
|
||||
)
|
||||
out["quantiles"] = {
|
||||
name: quantiles(method, route, clean)
|
||||
for name, (method, route) in events["routes"].items()
|
||||
}
|
||||
out["loki_counts"] = loki_counts(run)
|
||||
jobs = get(
|
||||
f"{PROMETHEUS}/api/v1/query",
|
||||
{"query": 'count by (job) ({__name__=~".+"})', "time": at},
|
||||
)
|
||||
out["series_by_job"] = {
|
||||
item["metric"].get("job", ""): int(float(item["value"][1]))
|
||||
for item in jobs["data"]["result"]
|
||||
}
|
||||
tsdb = get(f"{PROMETHEUS}/api/v1/status/tsdb")["data"]
|
||||
out["tsdb"] = {
|
||||
"num_series": tsdb.get("headStats", {}).get("numSeries"),
|
||||
"top_metrics": tsdb.get("seriesCountByMetricName", [])[:10],
|
||||
}
|
||||
config = get(f"{PROMETHEUS}/api/v1/status/config")["data"]["yaml"]
|
||||
tail = prom_value(
|
||||
'count({__name__=~"otelcol_processor_tail_sampling_.*"})',
|
||||
at,
|
||||
)
|
||||
out["layers"] = {
|
||||
"tail_sampling": bool(tail),
|
||||
"lean_prometheus": "loki_distributor_" in config,
|
||||
}
|
||||
out["seconds"] = round(time.monotonic() - started, 1)
|
||||
return out
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] == ["wait-ready"]:
|
||||
timeout = float(argv[2]) if argv[1:2] == ["--timeout"] else 90.0
|
||||
return wait_ready(timeout)
|
||||
if argv[:1] == ["collect"] and len(argv) == 3:
|
||||
with open(argv[1], encoding="utf-8") as file:
|
||||
events = json.load(file)
|
||||
try:
|
||||
result = collect(events)
|
||||
except TruncatedError as exc:
|
||||
print(str(exc), flush=True)
|
||||
return 1
|
||||
with open(argv[2], "w", encoding="utf-8") as file:
|
||||
json.dump(result, file, ensure_ascii=False, indent=1)
|
||||
print(f"lookup done in {result['seconds']}s", flush=True)
|
||||
return 0
|
||||
print(__doc__, flush=True)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -648,6 +648,23 @@ def fmt(value: float | None, digits: int = 1) -> str:
|
||||
return "—" if value is None else f"{value:.{digits}f}"
|
||||
|
||||
|
||||
def telemetry_line(profile: dict[str, Any]) -> str:
|
||||
"""Режим телеметрии метки (design change `track1-telemetry-cost`, решение
|
||||
13): у варианта «до» SDK в коде нет — с `on` сравнение смешанное."""
|
||||
if profile.get("telemetry") != "on":
|
||||
return "Телеметрия стенда выключена (TELEMETRY=off)"
|
||||
text = (
|
||||
"Телеметрия стенда включена (TELEMETRY=on): SDK реплики с настройками "
|
||||
"рабочего стенда, Collector, Prometheus, Loki и Tempo рабочего стенда"
|
||||
)
|
||||
if "before" in profile.get("uploads_variants", ()):
|
||||
text += (
|
||||
"; вариант «до» — образ кода без SDK, его сравнение с остальными "
|
||||
"вариантами смешанное (с телеметрией против без неё)"
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
"""`summary.md` метки: паспорт кратко, таблица ячеек (медиана и
|
||||
min–max повторов), сценарии спеков и гипотезы."""
|
||||
@@ -710,6 +727,7 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
"Значения — медиана (min–max) повторов",
|
||||
"- Посторонние контейнеры в VM во время замера: "
|
||||
+ (", ".join(meta.get("other_containers") or []) or "нет"),
|
||||
"- " + telemetry_line(profile),
|
||||
"",
|
||||
"## Ячейки",
|
||||
"",
|
||||
|
||||
Reference in New Issue
Block a user