From 515b3913a2d352e62fc608ee25fde9b7841322a1 Mon Sep 17 00:00:00 2001 From: CharaWein Date: Thu, 12 Nov 2026 13:15:29 +0300 Subject: [PATCH] =?UTF-8?q?lab6:=20=D1=80=D0=B0=D0=B7=D0=BC=D0=B5=D1=80=20?= =?UTF-8?q?=D0=BE=D1=87=D0=B5=D1=80=D0=B5=D0=B4=D0=B5=D0=B9=20Collector=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=20memory=5Flimiter,=20=D1=8F=D0=B2=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20frontend=5Fworker=20Tempo,=20=D0=B7=D0=B0=D0=B3?= =?UTF-8?q?=D0=BE=D0=BB=D0=BE=D0=B2=D0=BE=D0=BA=20traceresponse,=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=B2=D0=BE=D1=81?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BF=D0=BE=20ID=20=D1=82=D1=80=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- infra/otel/collector-tail.yaml | 9 ++++--- infra/otel/collector.yaml | 9 ++++--- infra/tempo/tempo.yaml | 5 ++++ .../transport/http/middleware/telemetry.go | 4 +++ student-tests/observability_ops.py | 27 +++++++++++++++---- 5 files changed, 43 insertions(+), 11 deletions(-) diff --git a/infra/otel/collector-tail.yaml b/infra/otel/collector-tail.yaml index 3d828ca..047d8b2 100644 --- a/infra/otel/collector-tail.yaml +++ b/infra/otel/collector-tail.yaml @@ -10,6 +10,9 @@ # ограниченной очереди), вместо бесконечного роста RSS; # batch — пакеты до 1024 элементов / 2 s; # sending_queue (in-memory, queue_size пакетов) + retry_on_failure (≤ 60 s) — +# размер подобран так, чтобы очередь целиком (20 пакетов × 1024 spans) помещалась +# ниже soft limit memory_limiter: при queue_size 200 и пакетах до 2048 очередь при +# отказе Tempo упиралась в hard limit, и Collector отвергал НОВЫЕ данные (прогон 4); # при недоступном Tempo/Loki данные ждут ограниченное время в ограниченной # очереди, затем отбрасываются и считаются в otelcol_exporter_send_failed_*. # Метрики не буферизуются вовсе: exporter prometheus хранит только текущее @@ -47,7 +50,7 @@ processors: spike_limit_mib: 50 batch: send_batch_size: 1024 - send_batch_max_size: 2048 + send_batch_max_size: 1024 timeout: 2s # Защита от утечек на случай ошибки инструментирования: такие ключи не должны # появляться, но если появятся — удаляются до экспорта. @@ -68,7 +71,7 @@ exporters: sending_queue: enabled: true num_consumers: 2 - queue_size: 200 + queue_size: 20 # ≤ 20 пакетов × ≤ 1024 элемента: очередь помещается в memory_limiter retry_on_failure: enabled: true initial_interval: 1s @@ -79,7 +82,7 @@ exporters: sending_queue: enabled: true num_consumers: 2 - queue_size: 200 + queue_size: 20 # ≤ 20 пакетов × ≤ 1024 элемента: очередь помещается в memory_limiter retry_on_failure: enabled: true initial_interval: 1s diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index 093ff84..a6e54df 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -7,6 +7,9 @@ # ограниченной очереди), вместо бесконечного роста RSS; # batch — пакеты до 1024 элементов / 2 s; # sending_queue (in-memory, queue_size пакетов) + retry_on_failure (≤ 60 s) — +# размер подобран так, чтобы очередь целиком (20 пакетов × 1024 spans) помещалась +# ниже soft limit memory_limiter: при queue_size 200 и пакетах до 2048 очередь при +# отказе Tempo упиралась в hard limit, и Collector отвергал НОВЫЕ данные (прогон 4); # при недоступном Tempo/Loki данные ждут ограниченное время в ограниченной # очереди, затем отбрасываются и считаются в otelcol_exporter_send_failed_*. # Метрики не буферизуются вовсе: exporter prometheus хранит только текущее @@ -26,7 +29,7 @@ processors: spike_limit_mib: 50 batch: send_batch_size: 1024 - send_batch_max_size: 2048 + send_batch_max_size: 1024 timeout: 2s # Защита от утечек на случай ошибки инструментирования: такие ключи не должны # появляться, но если появятся — удаляются до экспорта. @@ -47,7 +50,7 @@ exporters: sending_queue: enabled: true num_consumers: 2 - queue_size: 200 + queue_size: 20 # ≤ 20 пакетов × ≤ 1024 элемента: очередь помещается в memory_limiter retry_on_failure: enabled: true initial_interval: 1s @@ -58,7 +61,7 @@ exporters: sending_queue: enabled: true num_consumers: 2 - queue_size: 200 + queue_size: 20 # ≤ 20 пакетов × ≤ 1024 элемента: очередь помещается в memory_limiter retry_on_failure: enabled: true initial_interval: 1s diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml index b09cea2..2f889bf 100644 --- a/infra/tempo/tempo.yaml +++ b/infra/tempo/tempo.yaml @@ -10,6 +10,11 @@ distributor: protocols: grpc: endpoint: 0.0.0.0:4317 +# Явный адрес frontend для querier в single-binary: автоматическая настройка после +# рестарта Tempo оставляла запросы без ответа (прогон 4, отказ backend). +querier: + frontend_worker: + frontend_address: 127.0.0.1:9095 ingester: max_block_duration: 5m compactor: diff --git a/internal/transport/http/middleware/telemetry.go b/internal/transport/http/middleware/telemetry.go index 2490e32..8f40a3f 100644 --- a/internal/transport/http/middleware/telemetry.go +++ b/internal/transport/http/middleware/telemetry.go @@ -79,6 +79,10 @@ func Telemetry(next http.Handler) http.Handler { attribute.String("request_id", httputil.RequestIDFrom(r.Context())), )) defer span.End() + if sc := span.SpanContext(); sc.IsSampled() { + // W3C Trace Context Level 2: клиент (и тест) получает ID трассы своего запроса. + w.Header().Set("traceresponse", "00-"+sc.TraceID().String()+"-"+sc.SpanID().String()+"-01") + } methodAttr := attribute.String("http.request.method", r.Method) inflight.Add(ctx, 1, metric.WithAttributes(methodAttr)) defer inflight.Add(ctx, -1, metric.WithAttributes(methodAttr)) diff --git a/student-tests/observability_ops.py b/student-tests/observability_ops.py index aed30bc..0f0432e 100644 --- a/student-tests/observability_ops.py +++ b/student-tests/observability_ops.py @@ -399,13 +399,30 @@ def scenario_backend_down(c): compose('up', '-d', '--wait', '--no-deps', 'tempo', 'loki', timeout=180) t_up = time.time() rid = 'obs-after-' + uuid.uuid4().hex[:8] - c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': 'after'}, - headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid}) - # gRPC-клиент Collector переподключается к Tempo с экспоненциальной паузой (до 120 s): - # измеряем, через сколько секунд после возврата Tempo новые трассы снова доступны. - got = o.find_trace('{span.request_id="%s"}' % rid, t_up - 2, timeout=240) + sent0 = q('sum({__name__=~"otelcol_exporter_sent_spans(_total)?", exporter="otlp/tempo"})') + # Новые запросы после возврата Tempo; трасса ищется по ID из заголовка traceresponse + # (минуя поиск) — сначала каждые 5 s новый запрос, пока трасса не появится. + got, tids = None, [] + end = time.time() + 240 + while time.time() < end and not got: + r = c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': 'after'}, + headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid}) + tid = (r['headers'].get('traceresponse') or '--').split('-')[1] + tids.append(tid) + for t in tids: + try: + if o.tempo_trace(t)[0]: + got = t + break + except Exception: + pass + if not got: + time.sleep(5) + phase['tempo_spans_exported_after_up'] = q('sum({__name__=~"otelcol_exporter_sent_spans(_total)?", exporter="otlp/tempo"})') - sent0 + phase['refused_spans_total'] = q('sum({__name__=~"otelcol_receiver_refused_spans(_total)?"})') phase['new_trace_after_recovery'] = bool(got) phase['traces_visible_seconds_after_tempo_up'] = round(time.time() - t_up, 1) if got else None + phase['probe_requests_after_up'] = len(tids) # Фаза 2: остановлен сам Collector — SDK отбрасывает по ограниченной очереди compose('stop', 'otel-collector') t_cd = time.time()