#!/usr/bin/env python3 import subprocess import threading import time import uuid from client import Client, Failure, arguments, check, run from obs import alerts, loki, prom, prom_value, trace_search, wait_alert, wait_trace_spans from stack import compose, restore_worker, upload, wait_status class Load: def __init__(self, c, actor, chat, uploads=False, workers=3): self.c, self.actor, self.chat, self.uploads = c, actor, chat, uploads self.stop = threading.Event() self.codes = {} self.lock = threading.Lock() self.threads = [threading.Thread(target=self.loop, args=(i,)) for i in range(workers)] def record(self, code): with self.lock: self.codes[code] = self.codes.get(code, 0) + 1 def loop(self, index): while not self.stop.is_set(): try: if self.uploads and index == 0: self.c.call('POST', '/api/v1/chats/%s/attachments?filename=l-%s.png' % (self.chat['id'], uuid.uuid4().hex[:8]), [202, 503], actor=self.actor, raw=open('tests/fixtures/sample.png', 'rb').read(), headers={'Content-Type': 'image/png'}) self.record('upload') time.sleep(1) continue r = self.c.call('POST', '/api/v1/chats/%s/messages' % self.chat['id'], [201, 503], actor=self.actor, body={'text': 'load ' + uuid.uuid4().hex}, headers={'Idempotency-Key': uuid.uuid4().hex}) self.record(r['status']) except Failure as exc: self.record('failure') time.sleep(0.2) def __enter__(self): for t in self.threads: t.start() return self def __exit__(self, *exc): self.stop.set() for t in self.threads: t.join() def rss_mib(container): out = subprocess.run(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', container], capture_output=True, text=True).stdout value = out.split('/')[0].strip() number = float(''.join(ch for ch in value if ch.isdigit() or ch == '.')) return number * (1024 if value.endswith('GiB') else 1 if value.endswith('MiB') else 1 / 1024) def worker_stopped(c, alice, bob, chat): check(not alerts().get('QueueLagGrowing'), 'alert must start resolved') compose('stop', 'worker') stopped = time.time() with Load(c, alice, chat, uploads=True, workers=1): fired_after = wait_alert('QueueLagGrowing', True, 180) age = prom_value('max(queue_oldest_job_age_seconds)') depth = prom_value('max(queue_depth)') rate = prom_value('sum(rate(jobs_processed_total[1m]))', 0) busy = prom_value('sum(worker_busy)') stuck = trace_search('{ resource.service.name = "messenger-api" && name = "attachments.jobs publish" }', 5, stopped)[0] spans = wait_trace_spans(stuck['traceID'], lambda s: any(x['name'] == 'attachments.jobs publish' for x in s)) consumers = [s for s in spans if s['kind'] == 'SPAN_KIND_CONSUMER'] silent = loki('{service_name="messenger-worker"} | event="job ready"', 1, 5) check(not consumers, 'stuck job already has a consumer span') check(age is not None and age > 20 and depth and depth > 0, 'queue lag not visible in metrics') check(rate < 0.01, 'jobs still processed while worker is stopped') restart = time.monotonic() restore_worker() resolved_after = wait_alert('QueueLagGrowing', False, 180) deadline = time.monotonic() + 120 while prom_value('max(queue_depth)', 0) > 0 and time.monotonic() < deadline: time.sleep(2) drained = time.monotonic() - restart check(prom_value('max(queue_depth)', 0) == 0, 'backlog did not drain') print('1) worker stopped: QueueLagGrowing firing after %.0fs; oldest job age=%.0fs depth=%d jobs/s=%.2f worker_busy=%s' % (fired_after, age, depth, rate, busy)) print(' diagnosis from stored data: trace %s has the api server and "attachments.jobs publish" spans and no consumer span; ' 'no "job ready" worker log in Loki during the last minute (%d lines)' % (stuck['traceID'], len(silent))) print(' restored: worker started, alert resolved after %.0fs, backlog drained in %.0fs' % (resolved_after, drained)) def slow_database(c, alice, bob, chat): check(not alerts().get('ApiHighErrorRate'), 'alert must start resolved') lock = subprocess.Popen(['docker', 'compose', '--env-file', '.env', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', 'begin; lock table messages in access exclusive mode; select pg_sleep(45); commit;'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(2) with Load(c, alice, chat, workers=4) as load: fired_after = wait_alert('ApiHighErrorRate', True, 120) ratio = prom_value('sum(rate(http_server_requests_total{http_response_status_class="5xx"}[1m])) / sum(rate(http_server_requests_total[1m]))') by_route = {r['metric']['http_route']: float(r['value'][1]) for r in prom('sum by (http_route) (rate(http_server_requests_total{http_response_status_class="5xx"}[1m]))') if float(r['value'][1]) > 0} p99 = prom_value('histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[1m])))') used = prom_value('sum(db_pool_connections{state="used",job="messenger-api"})') wait = prom_value('sum(rate(db_pool_acquire_wait_seconds_total{job="messenger-api"}[1m]))', 0) errors = trace_search('{ resource.service.name = "messenger-api" && status = error && name =~ "POST .*messages" }', 5) check(errors, 'no error trace found') spans = wait_trace_spans(errors[0]['traceID'], lambda s: len(s) > 1) server = [s for s in spans if s['kind'] == 'SPAN_KIND_SERVER'][0] slow_db = max((s for s in spans if s['name'].startswith('db ')), key=lambda s: s['duration_us']) share = slow_db['duration_us'] / server['duration_us'] check(ratio and ratio > 0.05, 'error ratio not visible') check(share > 0.8 and slow_db['status'] == 'STATUS_CODE_ERROR', 'time is not spent in the database span') check(set(by_route) <= {'/api/v1/chats/{chat_id}/messages'}, 'unexpected failing routes: %s' % by_route) lock.wait(timeout=90) resolved_after = wait_alert('ApiHighErrorRate', False, 180) print('2) database lock on messages: ApiHighErrorRate firing after %.0fs; 5xx ratio=%.2f only on %s; p99=%.1fs; pool used=%s acquire wait=%.2f s/s' % (fired_after, ratio, sorted(by_route), p99 or 0, used, wait)) print(' diagnosis from stored data: error trace %s, server span %d ms, child "%s" %d ms (%.0f%%) with status error, ' 'handler has no other slow child; requests: %s' % (errors[0]['traceID'], server['duration_us'] // 1000, slow_db['name'], slow_db['duration_us'] // 1000, share * 100, load.codes)) print(' restored: lock released, alert resolved after %.0fs' % resolved_after) def storage_down(c, alice, bob, chat): stores = ['prometheus', 'loki', 'tempo'] container = compose('ps', '-q', 'otel-collector').stdout.strip() before = {name: prom_value('sum(%s)' % name, 0) for name in ('otelcol_exporter_send_failed_spans', 'otelcol_exporter_send_failed_log_records', 'otelcol_exporter_send_failed_metric_points')} peak = rss_mib(container) compose('stop', *stores) samples = [] attachments = [] try: with Load(c, alice, chat, uploads=True, workers=3) as load: for _ in range(20): time.sleep(4) samples.append(rss_mib(container)) codes = dict(load.codes) for _ in range(3): attachments.append(upload(c, alice, chat)['json']['id']) ready = [wait_status(c, bob, a, ('ready', 'failed'), 60)['status'] for a in attachments] msg = c.message(alice, chat, 'during outage') state = subprocess.run(['docker', 'inspect', '-f', '{{.RestartCount}} {{.State.OOMKilled}}', container], capture_output=True, text=True).stdout.split() finally: compose('up', '-d', '--wait', *stores) check(codes.get(201, 0) > 20 and 'failure' not in codes and 503 not in codes, 'API was affected by telemetry outage: %s' % codes) check(ready == ['ready'] * 3 and msg['status'] == 201, 'messages or jobs affected by telemetry outage') check(state == ['0', 'false'], 'collector restarted or was OOM killed') check(max(samples) < 230, 'collector memory unbounded: %.0f MiB' % max(samples)) time.sleep(30) after = {name: prom_value('sum(%s)' % name, 0) for name in before} check(after['otelcol_exporter_send_failed_spans'] > before['otelcol_exporter_send_failed_spans'], 'collector did not count dropped spans') exports = prom_value('sum(telemetry_export_errors_total)', 0) fresh = loki('{service_name="messenger-api"} | event="request"', 2, 5) check(fresh, 'logs did not resume after storage recovery') print('3) prometheus, loki and tempo stopped for ~80s under load: requests=%s, 3/3 uploads ready, message 201, no 5xx' % codes) print(' collector rss MiB: start=%.0f peak=%.0f during outage (limit 256, memory_limiter 160), restarts/oom=%s' % (peak, max(samples), ' '.join(state))) print(' telemetry lost and counted: collector send_failed spans +%d, log records +%d, metric points +%d; sdk export errors=%d' % (after['otelcol_exporter_send_failed_spans'] - before['otelcol_exporter_send_failed_spans'], after['otelcol_exporter_send_failed_log_records'] - before['otelcol_exporter_send_failed_log_records'], after['otelcol_exporter_send_failed_metric_points'] - before['otelcol_exporter_send_failed_metric_points'], exports)) print(' after restore new logs and metrics are stored again; data from the outage window is lost, data before it remains') def main(): def configure(p): p.add_argument('--only', choices=['worker', 'database', 'storage']) args = arguments('Controlled incidents with alerts and diagnosis from stored telemetry', configure) c = Client(args.base_url, args.ca_file, timeout=30) alice, bob, eve, chat = c.bootstrap() try: if args.only in (None, 'worker'): worker_stopped(c, alice, bob, chat) if args.only in (None, 'database'): slow_database(c, alice, bob, chat) if args.only in (None, 'storage'): storage_down(c, alice, bob, chat) finally: restore_worker() compose('up', '-d', '--no-deps', 'prometheus', 'loki', 'tempo', check_rc=False) print('PASS: ' + {'worker': 'stopped worker detected by alert and diagnosed from telemetry', 'database': 'slow database detected by alert and diagnosed from telemetry', 'storage': 'telemetry storage outage does not affect the API and loss is bounded and counted', None: 'two alerting incidents diagnosed from telemetry, storage outage does not affect the API'}[args.only]) if __name__ == '__main__': run(main)