Добавил наблюдаемость: OpenTelemetry, Prometheus, Loki, Tempo, Grafana

This commit is contained in:
gera
2026-11-19 23:10:55 +03:00
parent 470d9d6f1e
commit 4adc6c58c8
77 changed files with 8031 additions and 16 deletions
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
import hashlib
import uuid
from pathlib import Path
from client import Client, arguments, check, run
from image_gen import png, png_header_only
from stack import wait_status
ROOT = Path(__file__).resolve().parent.parent
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
MAX_BYTES = 10 * 1024 * 1024
def upload(c, actor, chat, data, expected, content_type='image/png', filename='file.png'):
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, expected,
actor=actor, raw=data, headers={'Content-Type': content_type},
schema='Attachment' if expected == 202 else None)
def post_message(c, actor, chat, ids, expected, text=''):
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', expected, actor=actor,
body={'text': text, 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message' if expected == 201 else None)
def main():
args = arguments('Attachment validation and access checks')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'second', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'eve', 'member_ids': [eve['id'], bob['id']]}, schema='Chat')['json']
upload(c, alice, chat, b'x' * (MAX_BYTES + 1), 413)
upload(c, alice, chat, SAMPLE + b'\0' * MAX_BYTES, 413)
upload(c, alice, chat, png_header_only(8000, 8000), 413)
upload(c, alice, chat, SAMPLE[:len(SAMPLE) // 2], 415)
upload(c, alice, chat, SAMPLE[:-1], 415)
upload(c, alice, chat, b'\x89PNG\r\n\x1a\n' + b'garbage' * 100, 415)
upload(c, alice, chat, b'', 415)
upload(c, alice, chat, b'GIF89a' + b'\0' * 64, 415)
upload(c, alice, chat, SAMPLE, 415, content_type='image/jpeg')
upload(c, alice, chat, SAMPLE, 415, content_type='text/plain')
upload(c, alice, chat, SAMPLE, 415, content_type='application/octet-stream')
for name in ('..%2Fx.png', 'a%5Cb.png', 'a%00b.png', 'a%0Ab.png', 'a' * 256, ''):
upload(c, alice, chat, SAMPLE, 400, filename=name)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
upload(c, eve, chat, SAMPLE, 404)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=a.png', 401, raw=SAMPLE, headers={'Content-Type': 'image/png'})
ok = upload(c, alice, chat, SAMPLE, 202)['json']
check(ok['sha256'] == hashlib.sha256(SAMPLE).hexdigest(), 'checksum mismatch')
check(ok['filename'] == 'file.png' and ok['status'] == 'queued' and ok['variants'] == [], 'attachment fields')
unicode_name = upload(c, alice, chat, SAMPLE, 202, filename='%D1%84%D0%BE%D1%82%D0%BE.png')['json']
check(unicode_name['filename'] == 'фото.png', 'unicode filename changed')
post_message(c, alice, other, [ok['id']], 404)
post_message(c, alice, chat, [str(uuid.uuid4())], 404)
post_message(c, alice, chat, [ok['id'], ok['id']], 400)
post_message(c, alice, chat, ['not-a-uuid'], 400)
post_message(c, alice, chat, [str(uuid.uuid4()) for _ in range(11)], 400)
post_message(c, alice, chat, [], 400)
post_message(c, eve, chat, [ok['id']], 404)
post_message(c, eve, eve_chat, [ok['id']], 404)
shared = post_message(c, bob, chat, [ok['id'], unicode_name['id']], 201, text='from bob')['json']
check(shared['attachment_ids'] == [ok['id'], unicode_name['id']], 'attachment order changed')
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice, schema='MessagePage')['json']['items']
check(any(m['id'] == shared['id'] and m['attachment_ids'] == shared['attachment_ids'] for m in history), 'history lost attachment_ids')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + ok['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
c.call('GET', '/api/v1/attachments/bad' + suffix, 400, actor=alice)
c.call('GET', '/api/v1/attachments/' + ok['id'] + suffix, 401)
c.call('GET', '/api/v1/attachments/' + ok['id'] + '/content?variant=bogus', 400, actor=bob)
wait_status(c, bob, ok['id'], ('ready',), 60)
download = c.call('GET', '/api/v1/attachments/' + ok['id'] + '/content', actor=bob)
check(download['bytes'] == SAMPLE, 'download differs')
big = png(1800, 1800, noise=True)
check(len(big) < MAX_BYTES, 'generated image exceeds limit')
large = upload(c, alice, chat, big, 202)['json']
wait_status(c, bob, large['id'], ('ready',), 60)
check(c.call('GET', '/api/v1/attachments/' + large['id'] + '/content', actor=bob)['bytes'] == big, 'large download differs')
print('PASS: attachment validation, limits and access control')
if __name__ == '__main__':
run(main)
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import base64
import json
import urllib.parse
import urllib.request
from pathlib import Path
from client import ROOT, arguments, check, run
GRAFANA = 'http://127.0.0.1:3000'
def call(method, path, body=None):
password = (ROOT / 'secrets/grafana_admin_password').read_text().strip()
request = urllib.request.Request(GRAFANA + path, data=json.dumps(body).encode() if body is not None else None, method=method,
headers={'Content-Type': 'application/json',
'Authorization': 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode()})
with urllib.request.urlopen(request, timeout=30) as response:
return json.loads(response.read())
def main():
arguments('Provisioned datasources and dashboard answer their queries through Grafana')
sources = {d['uid']: d['type'] for d in call('GET', '/api/datasources')}
check(sources == {'prometheus': 'prometheus', 'loki': 'loki', 'tempo': 'tempo'}, 'datasources not provisioned: %s' % sources)
found = call('GET', '/api/search?query=Messenger')
check([d['uid'] for d in found] == ['messenger-observability'], 'dashboard not provisioned')
dashboard = call('GET', '/api/dashboards/uid/messenger-observability')['dashboard']
on_disk = json.loads((ROOT / 'infra/grafana/dashboards/messenger.json').read_text())
check(len(dashboard['panels']) == len(on_disk['panels']), 'dashboard differs from the file in Git')
checked = 0
for panel in dashboard['panels']:
for target in panel.get('targets', []):
if panel['datasource']['type'] == 'tempo':
found = call('GET', '/api/datasources/proxy/uid/tempo/api/search?q=' + urllib.parse.quote(target['query']) + '&limit=5')
check('traces' in found, 'panel "%s" tempo search failed' % panel['title'])
checked += 1
continue
query = dict(target, intervalMs=15000, maxDataPoints=500)
result = call('POST', '/api/ds/query', {'queries': [query], 'from': 'now-30m', 'to': 'now'})['results'][target['refId']]
check('error' not in result and result.get('status', 200) == 200, 'panel "%s" query failed: %s' % (panel['title'], result.get('error')))
checked += 1
print('grafana: 3 datasources and dashboard "%s" provisioned from Git, %d panels, %d queries executed without errors'
% (dashboard['title'], len(dashboard['panels']), checked))
print('PASS: provisioning and dashboard queries')
if __name__ == '__main__':
run(main)
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python3
import json
import re
import time
import uuid
from client import Client, Failure, arguments, check, run
from stack import (SAMPLE, broker, compose, job_row, logs, now_iso, psql, restore_api, restore_worker, upload,
variant_count, wait_api, wait_log, wait_status)
def job_id_of(att_id):
return psql("select id from jobs where attachment_id='%s'" % att_id)
def worker_with(fault, **extra):
compose('up', '-d', '--force-recreate', '--no-deps', 'worker', env=dict({'WORKER_FAULT_POINT': fault}, **extra))
def wait_s3(timeout=90):
deadline = time.monotonic() + timeout
while '(healthy)' not in compose('ps', 's3', '--format', '{{.Status}}').stdout:
check(time.monotonic() < deadline, 's3 did not recover')
time.sleep(1)
def ops(*args):
out = compose('run', '--rm', '--no-deps', '-T', 'worker', *args).stdout
return [json.loads(line) for line in out.splitlines() if line.startswith('{')]
def crash_after_commit(c, alice, bob, chat):
since = now_iso()
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env={'API_FAULT_POINT': 'after_commit'})
compose('restart', 'lb')
wait_api(c)
name = 'crash-' + uuid.uuid4().hex[:12] + '.png'
answered = None
try:
answered = upload(c, alice, chat, filename=name)
except Failure:
pass
check(answered is None, 'api answered 202 despite injected crash')
wait_log('api', since, '"point":"after_commit"', 20)
att_id = psql("select id from attachments where filename='%s'" % name)
check(att_id, 'committed attachment not found')
restore_api(c)
ready = wait_status(c, bob, att_id, ('ready', 'failed'), 60)
check(ready['status'] == 'ready' and job_row(att_id)[:2] == ('ready', 1), 'outbox did not recover the job')
published = psql("select count(*) from outbox where job_id='%s' and published_at is not null" % job_id_of(att_id))
print('1) api crashed after COMMIT before 202/publish: attachment=%s recovered by outbox relay (published rows=%s) -> ready attempt=1'
% (att_id, published))
def crash_after_store(c, alice, bob, chat):
compose('stop', 'worker')
att = upload(c, alice, chat)['json']
since = now_iso()
worker_with('after_store', JOB_TIMEOUT_SECONDS='10')
wait_log('worker', since, '"point":"after_store"', 60)
status, attempt, _ = job_row(att['id'])
check(status == 'processing' and attempt == 1, 'job must stay processing under expired-to-be lease')
since = now_iso()
worker_with('', JOB_TIMEOUT_SECONDS='10')
wait_log('worker', since, '"lease expired","job_id":"%s"' % job_id_of(att['id']), 90)
ready = wait_status(c, bob, att['id'], ('ready', 'failed'), 60)
status, attempt, _ = job_row(att['id'])
check(ready['status'] == 'ready' and status == 'ready' and attempt >= 2, 'job did not finish after lease expiry')
check(variant_count(att['id']) == 3 and len(ready['variants']) == 3, 'retry duplicated variants')
thumb = [v for v in ready['variants'] if v['name'] == 'thumbnail'][0]
body = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=bob)['bytes']
check(len(body) == thumb['size_bytes'], 'thumbnail differs from metadata')
restore_worker()
print('2) worker crashed after S3 write before COMMIT: lease expired, reaper requeued, attempt=%d ready, variants=3' % attempt)
def crash_before_ack(c, alice, bob, chat):
compose('stop', 'worker')
att = upload(c, alice, chat)['json']
job_id = job_id_of(att['id'])
since = now_iso()
worker_with('before_ack')
wait_log('worker', since, '"point":"before_ack"', 60)
wait_log('worker', since, '"job delivery skipped","job_id":"%s"' % job_id, 60)
status, attempt, _ = job_row(att['id'])
check(status == 'ready' and attempt == 1 and variant_count(att['id']) == 3, 'redelivery after commit changed result')
check(broker('XPENDING', 'attachments.jobs', 'workers').splitlines()[0] == '0', 'redelivered message not acked')
check(wait_status(c, bob, att['id'], ('ready',), 10)['status'] == 'ready', 'attachment not ready')
restore_worker()
print('3) worker crashed after COMMIT before ack: message redelivered after restart, skipped as no-op, attempt=1, variants=3')
def retries_and_replay(c, alice, bob, chat):
compose('stop', 'worker')
att = upload(c, alice, chat)['json']
job_id = job_id_of(att['id'])
compose('stop', 's3')
since = now_iso()
try:
compose('up', '-d', '--no-deps', 'worker')
check('(healthy)' not in compose('ps', '-a', 's3', '--format', '{{.Status}}').stdout, 's3 must stay stopped')
failed = wait_status(c, bob, att['id'], ('failed', 'ready'), 120)
check(failed['status'] == 'failed' and failed['error_code'] == 'retry_exhausted', 'expected retry_exhausted')
text = logs('worker', since)
delays = [int(d) for d in re.findall(r'"job retry scheduled","job_id":"%s".*?"delay_ms":(\d+)' % job_id, text)]
check(len(delays) == 4, 'expected 4 scheduled retries, got %d' % len(delays))
for n, d in enumerate(delays):
base = 1000 * 2 ** n
check(base // 2 <= d <= base, 'delay %d outside jittered window for retry %d' % (d, n + 1))
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=bob)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(any(x['attachment_id'] == att['id'] for x in ops('failed')), 'failed registry misses job')
print('4) s3 down: transient errors retried with backoff+jitter delays_ms=%s, then failed retry_exhausted, listed in registry' % delays)
finally:
compose('start', 's3')
wait_s3()
check(ops('replay', att['id'])[0]['result'] == 'queued', 'replay did not queue job')
ready = wait_status(c, bob, att['id'], ('ready', 'failed'), 120)
check(ready['status'] == 'ready' and variant_count(att['id']) == 3, 'replayed job did not finish')
check(ops('replay', att['id'])[0]['result'] == 'skipped_ready', 'replay of ready job must be a no-op')
check(psql("select count(*) from job_replays where job_id='%s'" % job_id) == '1', 'replay audit missing')
check(variant_count(att['id']) == 3, 'second replay created new effects')
print(' replay: failed -> queued -> ready (audit rows=1); replay of ready job skipped, variants=3')
def permanent_error(c, alice, bob, chat):
data = bytearray(SAMPLE)
mid = len(data) // 2
data[mid:mid + 64] = b'\x00' * 64
att = upload(c, alice, chat, bytes(data))['json']
failed = wait_status(c, bob, att['id'], ('failed', 'ready'), 60)
status, attempt, _ = job_row(att['id'])
check(failed['status'] == 'failed' and failed['error_code'] == 'invalid_image' and attempt == 1, 'corrupt image must fail without retries')
check(failed['variants'] == [], 'failed attachment has variants')
print('5) corrupted IDAT (passes header/tail check in API): failed invalid_image on attempt 1, no retries')
def main():
args = arguments('Fault injection: COMMIT/publish gap, crash before COMMIT and before ack, retries, DLQ replay')
c = Client(args.base_url, args.ca_file, timeout=15)
alice, bob, eve, chat = c.bootstrap()
try:
crash_after_commit(c, alice, bob, chat)
crash_after_store(c, alice, bob, chat)
crash_before_ack(c, alice, bob, chat)
retries_and_replay(c, alice, bob, chat)
permanent_error(c, alice, bob, chat)
finally:
compose('up', '-d', '--no-deps', 's3')
restore_worker()
if 'after_commit' in compose('exec', '-T', 'api', 'printenv', 'FAULT_POINT', check_rc=False).stdout:
restore_api(c)
print('PASS: outbox recovery, lease recovery, redelivery after commit, backoff with jitter, retry_exhausted, replay, permanent error')
if __name__ == '__main__':
run(main)
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
import threading
import uuid
from client import Client, Failure, arguments, check, run
def main():
args = arguments('Concurrent Idempotency-Key check through the load balancer')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
parallel = 32
key = 'idem-' + uuid.uuid4().hex
barrier = threading.Barrier(parallel)
def send(_):
local = Client(args.base_url, args.ca_file)
barrier.wait()
return local.call('POST', path, 201, actor=alice, body={'text': 'same'}, headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=parallel) as pool:
results = list(pool.map(send, range(parallel)))
ids = {r['json']['id'] for r in results}
instances = {r['headers']['X-Instance-Id'] for r in results}
check(len(ids) == 1, 'parallel requests produced %d messages' % len(ids))
check(len(instances) >= 2, 'requests were served by one instance only')
check(len({r['json']['created_at'] for r in results}) == 1, 'created_at differs between replays')
listing = c.call('GET', path, actor=alice, schema='MessagePage')['json']['items']
check(sum(1 for m in listing if m['text'] == 'same') == 1, 'duplicate message in history')
c.call('POST', path, 409, actor=alice, body={'text': 'other'}, headers={'Idempotency-Key': key})
c.call('POST', path, 400, actor=alice, body={'text': 'x'})
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'bad key!'})
other = c.call('POST', path, 201, actor=bob, body={'text': 'same'}, headers={'Idempotency-Key': key}, schema='Message')['json']
check(other['id'] not in ids, 'key must be scoped per user')
print('PASS: %d parallel requests, 1 message, %d instances' % (parallel, len(instances)))
if __name__ == '__main__':
run(main)
+23
View File
@@ -0,0 +1,23 @@
import os
import struct
import zlib
def chunk(kind, data):
body = kind + data
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def png(width, height, noise=False):
header = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
raw = bytearray()
row = width * 3 + 1
for _ in range(height):
raw += b'\x00' + (os.urandom(row - 1) if noise else bytes(row - 1))
data = zlib.compress(bytes(raw), 0 if noise else 6)
return header + chunk(b'IDAT', data) + chunk(b'IEND', b'')
def png_header_only(width, height):
header = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
return header + chunk(b'IDAT', zlib.compress(b'\x00')) + chunk(b'IEND', b'')
+187
View File
@@ -0,0 +1,187 @@
#!/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)
+125
View File
@@ -0,0 +1,125 @@
import json
import time
import urllib.parse
import urllib.request
from client import Failure, check
PROM = 'http://127.0.0.1:9090'
LOKI = 'http://127.0.0.1:3100'
TEMPO = 'http://127.0.0.1:3200'
def get(url, params=None, timeout=10):
if params:
url += '?' + urllib.parse.urlencode(params)
with urllib.request.urlopen(url, timeout=timeout) as response:
return json.loads(response.read())
def prom(expr):
data = get(PROM + '/api/v1/query', {'query': expr})
check(data['status'] == 'success', 'prometheus query failed: ' + expr)
return data['data']['result']
def prom_value(expr, default=None):
result = prom(expr)
if not result:
return default
value = float(result[0]['value'][1])
return default if value != value else value
def series(name):
return get(PROM + '/api/v1/series', {'match[]': name})['data']
def alerts():
return {a['labels']['alertname']: a['state'] for a in get(PROM + '/api/v1/alerts')['data']['alerts']}
def wait_alert(name, firing, timeout=120):
deadline = time.monotonic() + timeout
started = time.monotonic()
while time.monotonic() < deadline:
state = alerts().get(name)
if (state == 'firing') == firing:
return time.monotonic() - started
time.sleep(2)
raise Failure('alert %s did not become %s' % (name, 'firing' if firing else 'resolved'))
def loki(query, minutes=15, limit=200):
end = time.time()
data = get(LOKI + '/loki/api/v1/query_range', {
'query': query, 'limit': limit, 'direction': 'backward',
'start': int((end - minutes * 60) * 1e9), 'end': int((end + 60) * 1e9)})
rows = []
for stream in data['data']['result']:
for ts, line in stream['values']:
rows.append((int(ts), stream['stream'], line))
return sorted(rows, key=lambda r: r[0])
def wait_loki(query, timeout=40, **kw):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
rows = loki(query, **kw)
if rows:
return rows
time.sleep(2)
raise Failure('loki returned nothing for ' + query)
def trace(trace_id, timeout=40):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
return flatten(get(TEMPO + '/api/traces/' + trace_id))
except Exception:
time.sleep(2)
raise Failure('tempo has no trace ' + trace_id)
def attrs(items):
out = {}
for a in items:
v = a['value']
out[a['key']] = v.get('stringValue', v.get('intValue', v.get('boolValue', v.get('doubleValue'))))
return out
def flatten(data):
spans = []
for batch in data.get('batches', []):
service = attrs(batch['resource']['attributes']).get('service.name')
for scope in batch['scopeSpans']:
for s in scope['spans']:
spans.append({
'service': service, 'name': s['name'], 'kind': s['kind'], 'id': s['spanId'],
'parent': s.get('parentSpanId', ''), 'start': int(s['startTimeUnixNano']),
'duration_us': (int(s['endTimeUnixNano']) - int(s['startTimeUnixNano'])) // 1000,
'attributes': attrs(s.get('attributes', [])), 'status': s.get('status', {}).get('code', ''),
})
return sorted(spans, key=lambda s: s['start'])
def trace_search(query, limit=20, since=None):
params = {'q': query, 'limit': limit}
if since:
params.update(start=int(since), end=int(time.time()) + 60)
return get(TEMPO + '/api/search', params).get('traces', [])
def wait_trace_spans(trace_id, predicate, timeout=60):
deadline = time.monotonic() + timeout
spans = []
while time.monotonic() < deadline:
try:
spans = trace(trace_id, 5)
except Failure:
spans = []
if spans and predicate(spans):
return spans
time.sleep(2)
raise Failure('trace %s did not reach the expected shape' % trace_id)
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
import json
import re
import time
import uuid
from client import Client, arguments, check, run
from faults import ops, wait_s3
from obs import loki, prom, series, wait_loki, wait_trace_spans
from stack import compose, restore_worker, upload, wait_status
SIGNALS = [
'http_server_requests_total', 'http_server_request_duration_seconds_bucket', 'jobs_processed_total',
'job_processing_duration_seconds_bucket', 'job_time_to_ready_seconds_bucket', 'queue_depth',
'queue_oldest_job_age_seconds', 'db_pool_connections', 'db_pool_max_connections', 'worker_busy',
'worker_capacity', 'process_cpu_time_seconds_total', 'process_memory_usage_bytes',
]
FORBIDDEN = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename', 'url', 'http_url', 'path', 'text'}
UUID = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-')
def signals_and_labels():
for name in SIGNALS:
check(prom('count(%s)' % name), 'metric %s has no samples' % name)
seen = set()
for name in SIGNALS:
for s in series(name):
seen |= set(s) - {'__name__'}
check(not UUID.search(s.get('http_route', '')), 'raw identifier in route label')
check(not (seen & FORBIDDEN), 'high-cardinality labels present: %s' % sorted(seen & FORBIDDEN))
routes = {s['http_route'] for s in series('http_server_requests_total')}
check('/api/v1/chats/{chat_id}/messages' in routes, 'route template missing')
print('metrics: %d signals present, labels=%s, routes are templates (%d)' % (len(SIGNALS), sorted(seen), len(routes)))
def chain(c, alice, bob, chat):
resp = upload(c, alice, chat)
request_id = resp['headers']['X-Request-Id']
att = resp['json']
ready = wait_status(c, bob, att['id'], ('ready', 'failed'), 60)
check(ready['status'] == 'ready', 'attachment did not become ready')
rows = wait_loki('{service_name="messenger-api"} | event="request" | request_id="%s"' % request_id)
trace_id = rows[-1][1].get('trace_id')
check(trace_id and re.fullmatch(r'[0-9a-f]{32}', trace_id), 'request log has no trace_id')
check(rows[-1][1].get('span_id'), 'request log has no span_id')
spans = wait_trace_spans(trace_id, lambda s: any(x['kind'] == 'SPAN_KIND_CONSUMER' for x in s)
and any(x['name'] == 'db COMMIT' and x['service'] == 'messenger-worker' for x in s)
and any(x['name'] == 's3 remove' for x in s))
by_id = {s['id']: s for s in spans}
server = [s for s in spans if s['kind'] == 'SPAN_KIND_SERVER'][0]
producer = [s for s in spans if s['kind'] == 'SPAN_KIND_PRODUCER'][0]
consumer = [s for s in spans if s['kind'] == 'SPAN_KIND_CONSUMER'][0]
check(server['service'] == 'messenger-api' and producer['service'] == 'messenger-api', 'producer must belong to api')
check(consumer['service'] == 'messenger-worker', 'consumer must belong to worker')
check(producer['parent'] == server['id'], 'producer span is not a child of the request span')
check(consumer['parent'] == producer['id'], 'consumer span is not a child of the producer span')
check(consumer['attributes'].get('attachment.id') == att['id'], 'consumer span misses attachment.id')
names = {(s['service'], s['name']) for s in spans}
for want in [('messenger-api', 's3 put'), ('messenger-api', 'db INSERT'), ('messenger-worker', 's3 get'),
('messenger-worker', 'image render'), ('messenger-worker', 's3 put'), ('messenger-worker', 'db COMMIT'),
('messenger-worker', 's3 remove')]:
check(want in names, 'span %s missing' % (want,))
check(all(s['parent'] in by_id or not s['parent'] for s in spans), 'orphan spans in trace')
worker_logs = wait_loki('{service_name="messenger-worker"} | event="job ready" | trace_id="%s"' % trace_id)
check(worker_logs[-1][1].get('span_id'), 'worker log has no span_id')
print('chain: request_id=%s trace_id=%s spans=%d api->producer->consumer->s3/db linked, api and worker logs carry trace_id'
% (request_id, trace_id, len(spans)))
return att, trace_id
def secrets(c, alice, chat, trace_id):
marker = 'secret-body-' + uuid.uuid4().hex
resp = c.message(alice, chat, marker)
request_id = resp['headers']['X-Request-Id']
time.sleep(8)
rows = wait_loki('{service_name="messenger-api"} | event="request" | request_id="%s"' % request_id)
message_trace = rows[-1][1].get('trace_id')
raw = json.dumps(wait_trace_spans(message_trace, lambda s: len(s) > 1)) + json.dumps(wait_trace_spans(trace_id, lambda s: True))
for needle, what in ((marker, 'message body'), (alice['token'], 'session token')):
check(needle not in raw, '%s leaked into traces' % what)
check(not loki('{service_name=~"messenger-.*"} |= "%s"' % needle), '%s leaked into logs' % what)
check(not loki('{service_name=~"messenger-.*"} |~ "(?i)authorization|bearer "'), 'authorization material in logs')
print('secrets: message body and session token absent from Loki and Tempo')
def retry_trace(c, alice, bob, chat):
compose('stop', 'worker')
att = upload(c, alice, chat)['json']
compose('stop', 's3')
try:
compose('up', '-d', '--no-deps', 'worker')
failed = wait_status(c, bob, att['id'], ('failed', 'ready'), 120)
check(failed['status'] == 'failed', 'expected retry_exhausted while S3 is down')
finally:
compose('start', 's3')
wait_s3()
check(ops('replay', att['id'])[0]['result'] == 'queued', 'replay did not queue job')
check(wait_status(c, bob, att['id'], ('ready', 'failed'), 120)['status'] == 'ready', 'replay did not finish')
rows = wait_loki('{service_name="messenger-worker"} | event="job ready" | attachment_id="%s"' % att['id'])
trace_id = rows[-1][1]['trace_id']
spans = wait_trace_spans(trace_id, lambda s: sum(x['kind'] == 'SPAN_KIND_CONSUMER' for x in s) >= 6
and any(x['name'] == 'db COMMIT' for x in s))
consumers = [s for s in spans if s['kind'] == 'SPAN_KIND_CONSUMER']
attempts = sorted(int(s['attributes']['job.attempt']) for s in consumers)
check(attempts == list(range(1, len(attempts) + 1)), 'attempts are not sequential: %s' % attempts)
errors = [s for s in consumers if s['status'] == 'STATUS_CODE_ERROR']
check(len(errors) == 5, 'expected 5 failed attempts in the trace, got %d' % len(errors))
check(sum(1 for s in spans if s['kind'] == 'SPAN_KIND_PRODUCER') == len(consumers), 'each attempt needs its publish span')
print('retry: one trace %s holds %d attempts (%d failed with S3 down, attempt %d ready after replay)'
% (trace_id, len(consumers), len(errors), attempts[-1]))
def main():
args = arguments('Observability signals, trace propagation, correlation and redaction')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
try:
att, trace_id = chain(c, alice, bob, chat)
signals_and_labels()
secrets(c, alice, chat, trace_id)
retry_trace(c, alice, bob, chat)
finally:
compose('start', 's3', check_rc=False)
restore_worker()
print('PASS: signals, producer/consumer trace chain, log correlation, retry in trace, no secrets in telemetry')
if __name__ == '__main__':
run(main)
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
import json
import time
from client import Client, arguments, check, run
from image_probe import jpeg_size
from stack import broker, compose, job_row, logs, now_iso, psql, upload, variant_count, wait_api, wait_log, wait_status
def stream_has(job_id):
return job_id in broker('XRANGE', 'attachments.jobs', '-', '+')
def main():
args = arguments('Worker stop, API/broker restart and redelivery scenario')
c = Client(args.base_url, args.ca_file, timeout=15)
alice, bob, eve, chat = c.bootstrap()
compose('stop', 'worker')
try:
att = upload(c, alice, chat)['json']
check(att['status'] == 'queued' and att['variants'] == [], 'upload must return queued snapshot')
msg = c.message(alice, chat, '', attachments=[att['id']])['json']
check(msg['attachment_ids'] == [att['id']], 'message lost queued attachment')
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 409, actor=bob)
c.message(bob, chat, 'text works while worker is down')
job_id = psql("select id from jobs where attachment_id='%s'" % att['id'])
deadline = time.monotonic() + 10
while not stream_has(job_id):
check(time.monotonic() < deadline, 'job was not published to broker')
time.sleep(0.5)
check(psql("select count(*) from outbox where job_id='%s' and published_at is null" % job_id) == '0', 'outbox not marked')
print('accepted: attachment=%s job=%s status=queued, job in stream, worker stopped' % (att['id'], job_id))
compose('restart', 'broker', 'api')
compose('up', '-d', '--wait', '--no-deps', 'broker', 'api')
compose('restart', 'lb')
wait_api(c)
check(stream_has(job_id), 'job lost after broker restart')
check(c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']['status'] == 'queued', 'status changed without worker')
print('restarted broker and api: job still in stream, attachment still queued')
finally:
compose('start', 'worker')
ready = wait_status(c, bob, att['id'], ('ready', 'failed'), 60)
check(ready['status'] == 'ready', 'job did not finish after worker start')
thumb = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=bob)
check(jpeg_size(thumb['bytes']) == (256, 160), 'thumbnail size')
check(job_row(att['id'])[:2] == ('ready', 1) and variant_count(att['id']) == 3, 'unexpected job state or variants')
print('worker started: attachment ready, attempt=1, variants=3')
since = now_iso()
before = psql("select updated_at from attachments where id='%s'" % att['id'])
payload = json.dumps({'schema_version': 1, 'job_id': job_id, 'type': 'attachment.process.v1', 'attachment_id': att['id'],
'pipeline_version': 1, 'attempt': 1, 'created_at': ready['created_at']})
broker('XADD', 'attachments.jobs', '*', 'job', payload)
wait_log('worker', since, '"job delivery skipped","job_id":"%s"' % job_id, 30)
time.sleep(1)
check(psql("select updated_at from attachments where id='%s'" % att['id']) == before, 'duplicate delivery changed attachment')
check(variant_count(att['id']) == 3 and job_row(att['id'])[:2] == ('ready', 1), 'duplicate delivery created new effects')
pending = broker('XPENDING', 'attachments.jobs', 'workers')
check(pending.splitlines()[0] == '0', 'duplicate message was not acked')
print('duplicate delivery: skipped as no-op, acked, variants=3, updated_at unchanged')
print('PASS: worker stop, broker/api restart, redelivery idempotency')
if __name__ == '__main__':
run(main)
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
import hashlib
import subprocess
import time
import uuid
from pathlib import Path
from client import Client, Failure, arguments, check, run
from stack import wait_status
ROOT = Path(__file__).resolve().parent.parent
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
BUCKET = 'messenger-attachments'
def compose(*args, check_rc=True, stdin=None):
return subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, check=check_rc,
capture_output=True, text=True, input=stdin)
def secret(name):
return (ROOT / 'secrets' / name).read_text().strip()
def s3_status(method, path, user=None, data=None):
cmd = ['exec', '-T', 's3', 'curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', '-X', method]
if user:
cmd += ['--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', user[0] + ':' + user[1]]
if data is not None:
cmd += ['--data-binary', data]
cmd.append('http://127.0.0.1:9000' + path)
return compose(*cmd).stdout.strip()
def upload(c, actor, chat, expected):
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=a.png', expected, actor=actor,
raw=SAMPLE, headers={'Content-Type': 'image/png'}, schema='Attachment' if expected == 202 else None)
def wait_api(c):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready')
return
except Failure:
time.sleep(1)
raise Failure('api did not recover')
def wait_s3(timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if compose('ps', 's3', '--format', '{{.Status}}').stdout.count('(healthy)'):
return
time.sleep(1)
raise Failure('s3 did not recover')
def object_key(attachment_id):
out = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc',
"select object_key from attachments where id='%s'" % attachment_id).stdout.strip()
check(out.startswith('attachments/'), 'object key not found')
return out
def main():
args = arguments('S3 privacy, outage and orphan cleanup checks')
c = Client(args.base_url, args.ca_file, timeout=15)
alice, bob, eve, chat = c.bootstrap()
att = upload(c, alice, chat, 202)['json']
wait_status(c, bob, att['id'], ('ready',), 60)
key = object_key(att['id'])
check(key != 'attachments/' + att['filename'] and att['filename'] not in key, 'object key derived from filename')
api = (secret('s3_access_key_id'), secret('s3_secret_access_key'))
admin = (secret('s3_admin_access_key_id'), secret('s3_admin_secret_access_key'))
path = '/' + BUCKET + '/' + key
check(s3_status('GET', path) == '403', 'anonymous GET must be denied')
check(s3_status('GET', '/' + BUCKET + '/') == '403', 'anonymous listing must be denied')
check(s3_status('PUT', path + '-anon', data='x') == '403', 'anonymous PUT must be denied')
check(s3_status('GET', path, ('wrong', 'wrong')) == '403', 'wrong credentials must be denied')
check(s3_status('GET', path, api) == '200', 'api credentials cannot read')
check(s3_status('PUT', '/other-bucket-' + uuid.uuid4().hex[:8], api) == '403', 'api credentials can create buckets')
ports = compose('ps', '--format', '{{.Service}} {{.Ports}}').stdout
lines = [line for line in ports.splitlines() if '->' in line]
published = [line.split()[0] for line in lines]
check(sorted(published) == ['grafana', 'lb', 'loki', 'prometheus', 'tempo'], 'unexpected published services: %s' % published)
check(all(part.startswith('127.0.0.1:') for line in lines for part in line.split(None, 1)[1].split(', ') if '->' in part),
'published ports must be bound to 127.0.0.1')
compose('stop', 's3')
try:
upload(c, alice, chat, 503)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')
c.message(alice, chat, 'text works while s3 is down')
finally:
compose('start', 's3')
wait_s3()
wait_api(c)
deadline = time.monotonic() + 60
while True:
try:
body = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes']
check(body == SAMPLE, 'content differs after s3 restart')
break
except Failure:
check(time.monotonic() < deadline, 'download did not recover')
time.sleep(1)
upload(c, alice, chat, 202)
orphan = '/' + BUCKET + '/attachments/' + uuid.uuid4().hex
check(s3_status('PUT', orphan, admin, 'orphan') == '200', 'cannot create orphan')
compose('run', '--rm', '--no-deps', '-e', 'CLEANUP_GRACE_SECONDS=3600', 'janitor', 'cleanup')
check(s3_status('GET', orphan, admin) == '200', 'fresh object was removed inside grace period')
time.sleep(1)
compose('run', '--rm', '--no-deps', '-e', 'CLEANUP_GRACE_SECONDS=0', 'janitor', 'cleanup')
check(s3_status('GET', orphan, admin) == '404', 'orphan was not removed')
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == SAMPLE, 'referenced object was removed')
check(s3_status('GET', '/' + BUCKET + '/staging/' + att['id'], admin) == '404', 'staging kept after ready')
stale = '/' + BUCKET + '/staging/' + str(uuid.uuid4())
check(s3_status('PUT', stale, admin, 'stale') == '200', 'cannot create stale staging object')
compose('stop', 'worker')
try:
queued = upload(c, alice, chat, 202)['json']
compose('run', '--rm', '--no-deps', '-e', 'CLEANUP_GRACE_SECONDS=0', 'janitor', 'cleanup')
check(s3_status('GET', '/' + BUCKET + '/staging/' + queued['id'], admin) == '200', 'staging of queued job was removed')
check(s3_status('GET', stale, admin) == '404', 'unreferenced staging object was not removed')
finally:
compose('up', '-d', '--no-deps', 'worker')
check(wait_status(c, bob, queued['id'], ('ready', 'failed'), 60)['status'] == 'ready', 'queued job lost staging')
print('PASS: private bucket, limited credentials, s3 outage, orphan and staging cleanup')
if __name__ == '__main__':
run(main)
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
import json
import subprocess
import threading
import time
import uuid
from pathlib import Path
from client import Client, Failure, arguments, check, run
ROOT = Path(__file__).resolve().parent.parent
def sh(*cmd):
return subprocess.run(cmd, cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
def api_containers():
out = sh('docker', 'compose', '--env-file', '.env', 'ps', '-q', 'api')
return [x[:12] for x in out.split()]
def wait_healthy(count, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
out = sh('docker', 'compose', '--env-file', '.env', 'ps', 'api', '--format', '{{.Status}}')
if out.count('(healthy)') >= count:
return
time.sleep(1)
raise Failure('replicas did not become healthy')
class Load:
def __init__(self, base, ca, concurrency):
c = Client(base, ca)
self.alice, _, _, self.chat = c.bootstrap()
self.base, self.ca, self.n = base, ca, concurrency
self.events = []
self.lock = threading.Lock()
self.stop = threading.Event()
self.t0 = time.monotonic()
def worker(self):
c = Client(self.base, self.ca, timeout=3)
while not self.stop.is_set():
key = uuid.uuid4().hex
first_error = None
while not self.stop.is_set():
try:
r = c.message(self.alice, self.chat, 'k-' + key, key=key)
t = time.monotonic() - self.t0
with self.lock:
self.events.append((t, True, r['headers']['X-Instance-Id'], first_error))
break
except Failure:
t = time.monotonic() - self.t0
first_error = first_error or t
with self.lock:
self.events.append((t, False, None, None))
time.sleep(0.05)
def start(self):
self.pool = ThreadPoolExecutor(max_workers=self.n)
self.futures = [self.pool.submit(self.worker) for _ in range(self.n)]
def finish(self):
self.stop.set()
self.pool.shutdown(wait=True)
def summary(self, begin, end):
ev = [e for e in self.events if begin <= e[0] < end]
ok = [e for e in ev if e[1]]
bad = [e for e in ev if not e[1]]
span = max(end - begin, 1e-9)
return {
'window_seconds': round(span, 2),
'successful_requests': len(ok),
'failed_attempts': len(bad),
'successful_rps': round(len(ok) / span, 1),
'last_error_offset_seconds': round(max(e[0] for e in bad) - begin, 2) if bad else None,
'instances': sorted({e[2] for e in ok}),
}
def instances_between(self, begin, end=float('inf')):
return sorted({e[2] for e in self.events if e[1] and begin <= e[0] < end})
def failover_each(args):
ids = api_containers()
check(len(ids) >= 2, 'need at least two replicas')
load = Load(args.base_url, args.ca_file, args.concurrency)
load.start()
time.sleep(args.warmup)
results = []
base = load.summary(2, args.warmup)
for target in ids:
before = time.monotonic() - load.t0
sh('docker', 'stop', '-t', '10', target)
stopped = time.monotonic() - load.t0
time.sleep(args.hold)
after_stop = time.monotonic() - load.t0
window = load.summary(before, after_stop)
sh('docker', 'start', target)
wait_healthy(len(ids))
restored = time.monotonic() - load.t0
time.sleep(args.warmup)
results.append({
'stopped_replica': target,
'during_failure': window,
'seen_stopped_replica_after_stop': target in load.instances_between(stopped + 0.5, after_stop),
'stop_command_seconds': round(stopped - before, 2),
'restore_seconds': round(restored - after_stop, 2),
'after_restore': load.summary(restored + 1, restored + args.warmup),
})
load.finish()
return {'baseline': base, 'replicas': results}
def rolling(args):
old = api_containers()
check(len(old) >= 2, 'need at least two replicas')
n = len(old)
load = Load(args.base_url, args.ca_file, args.concurrency)
load.start()
time.sleep(args.warmup)
begin = time.monotonic() - load.t0
sh('scripts/rolling-update.sh')
end = time.monotonic() - load.t0
time.sleep(args.warmup)
load.finish()
return {
'old_replicas': old,
'new_replicas': api_containers(),
'update_window': load.summary(begin, end),
'old_replicas_served_after_update': [i for i in load.instances_between(end) if i in old],
}
def main():
def configure(p):
p.add_argument('--mode', choices=['failover-each', 'rolling'], required=True)
p.add_argument('--concurrency', type=int, default=8)
p.add_argument('--warmup', type=float, default=8)
p.add_argument('--hold', type=float, default=12)
p.add_argument('--output')
args = arguments('Failure and rolling update under load', configure)
report = failover_each(args) if args.mode == 'failover-each' else rolling(args)
text = json.dumps(report, indent=2)
if args.output:
Path(args.output).write_text(text + '\n')
print(text)
if __name__ == '__main__':
run(main)
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
import time
from client import Client, arguments, check, run
from stack import compose
def wait_valkey(timeout=60):
deadline = time.monotonic() + timeout
while '(healthy)' not in compose('ps', 'valkey', '--format', '{{.Status}}').stdout:
check(time.monotonic() < deadline, 'valkey did not recover')
time.sleep(1)
def main():
args = arguments('Session revocation must not depend on the cache')
c = Client(args.base_url, args.ca_file, timeout=15)
alice, bob, eve, chat = c.bootstrap()
c.call('GET', '/api/v1/chats', 200, actor=alice)
compose('stop', 'valkey')
try:
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
finally:
compose('start', 'valkey')
wait_valkey()
c.call('GET', '/api/v1/chats', 401, actor=alice)
c.call('GET', '/api/v1/chats', 200, actor=bob)
print('PASS: token revoked while valkey was stopped stays revoked after valkey restart (401)')
if __name__ == '__main__':
run(main)
+92
View File
@@ -0,0 +1,92 @@
import os
import subprocess
import time
import uuid
from pathlib import Path
from client import Failure, check
ROOT = Path(__file__).resolve().parent.parent
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
def compose(*args, env=None, check_rc=True):
full = dict(os.environ, **(env or {}))
return subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, check=check_rc,
capture_output=True, text=True, env=full)
def psql(sql):
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', sql).stdout.strip()
def broker(*args):
cmd = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/broker_conf)" ' + ' '.join("'%s'" % a for a in args)
return compose('exec', '-T', 'broker', 'sh', '-c', cmd).stdout.strip()
def logs(service, since):
return compose('logs', '--no-color', '--since', since, service).stdout
def now_iso():
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
def upload(c, actor, chat, data=SAMPLE, content_type='image/png', filename=None, expected=202):
filename = filename or 'f-' + uuid.uuid4().hex[:12] + '.png'
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, expected, actor=actor,
raw=data, headers={'Content-Type': content_type}, schema='Attachment' if expected == 202 else None)
def wait_status(c, actor, att_id, statuses, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
att = c.call('GET', '/api/v1/attachments/' + att_id, actor=actor, schema='Attachment')['json']
if att['status'] in statuses:
return att
except Failure:
pass
time.sleep(0.5)
raise Failure('attachment %s did not reach %s' % (att_id, statuses))
def wait_api(c, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready')
return
except Failure:
time.sleep(1)
raise Failure('api did not become ready')
def wait_log(service, since, needle, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if needle in logs(service, since):
return
time.sleep(1)
raise Failure('%s did not log %r' % (service, needle))
def job_row(att_id):
out = psql("select status, attempt, coalesce(last_error, '') from jobs where attachment_id='%s'" % att_id)
check(out, 'job not found')
status, attempt, error = out.split('|', 2)
return status, int(attempt), error
def variant_count(att_id):
return int(psql("select count(*) from attachment_variants where attachment_id='%s'" % att_id))
def restore_worker():
compose('up', '-d', '--force-recreate', '--no-deps', 'worker', env={'WORKER_FAULT_POINT': ''})
def restore_api(c):
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', 'api', env={'API_FAULT_POINT': ''})
compose('restart', 'lb')
wait_api(c)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
import re
import time
from client import Client, arguments, check, run
from obs import loki, prom, trace, wait_loki
from stack import compose, upload, wait_status
def main():
args = arguments('Telemetry history survives a restart of the storages')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
request_id = upload(c, alice, chat)['headers']['X-Request-Id']
rows = wait_loki('{service_name="messenger-api"} | event="request" | request_id="%s"' % request_id)
trace_id = rows[-1][1]['trace_id']
check(re.fullmatch(r'[0-9a-f]{32}', trace_id), 'no trace_id in log')
time.sleep(15)
before = len(trace(trace_id))
samples = prom('count_over_time(http_server_requests_total[10m])')
check(before > 1 and samples, 'nothing to compare')
compose('restart', 'prometheus', 'loki', 'tempo')
compose('up', '-d', '--wait', 'prometheus', 'loki', 'tempo', 'grafana')
check(len(trace(trace_id, 90)) == before, 'trace lost after restart')
check(wait_loki('{service_name="messenger-api"} | event="request" | request_id="%s"' % request_id, 90), 'log lost after restart')
check(prom('count_over_time(http_server_requests_total[10m])'), 'metrics lost after restart')
print('persistence: trace %s (%d spans), its request log and %d metric series survived a restart of prometheus, loki and tempo'
% (trace_id, before, len(samples)))
print('PASS: telemetry history is kept on volumes')
if __name__ == '__main__':
run(main)
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import re
import subprocess
import threading
import time
from pathlib import Path
from client import Client, Failure, arguments, check, run
from image_gen import png
ROOT = Path(__file__).resolve().parent.parent
UNITS = {'B': 1, 'KiB': 1024, 'MiB': 1024 ** 2, 'GiB': 1024 ** 3}
def to_mib(text):
value, unit = re.match(r'([\d.]+)\s*([A-Za-z]+)', text).groups()
return float(value) * UNITS[unit] / 1024 ** 2
def sample(stop, peaks):
proc = subprocess.Popen(['docker', 'stats', '--format', '{{.Name}} {{.MemUsage}}'], cwd=ROOT,
stdout=subprocess.PIPE, text=True)
try:
for line in proc.stdout:
line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', line).strip()
m = re.match(r'(\S+-api-\d+)\s+(\S+ ?\S+) /', line)
if m:
peaks[m.group(1)] = max(peaks.get(m.group(1), 0), to_mib(m.group(2)))
if stop.is_set():
break
finally:
proc.terminate()
def main():
def configure(p):
p.add_argument('--concurrency', type=int, default=12)
p.add_argument('--rounds', type=int, default=3)
p.add_argument('--output')
args = arguments('Concurrent upload memory experiment', configure)
check(args.concurrency >= 10, 'use at least 10 concurrent uploads')
c = Client(args.base_url, args.ca_file, timeout=60)
alice, bob, eve, chat = c.bootstrap()
data = png(1800, 1800, noise=True)
digest = hashlib.sha256(data).hexdigest()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png'
idle, stop = {}, threading.Event()
t = threading.Thread(target=sample, args=(stop, idle))
t.start()
time.sleep(4)
stop.set()
t.join()
peaks, stop = {}, threading.Event()
t = threading.Thread(target=sample, args=(stop, peaks))
t.start()
time.sleep(2)
barrier = threading.Barrier(args.concurrency)
results = []
def worker(_):
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait()
out = []
for _ in range(args.rounds):
try:
r = local.call('POST', path, 202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
out.append(r['json']['sha256'] == digest)
except Failure:
out.append(False)
return out
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
for out in pool.map(worker, range(args.concurrency)):
results.extend(out)
elapsed = time.monotonic() - started
time.sleep(2)
stop.set()
t.join()
limit = 192
report = {
'file_bytes': len(data),
'concurrent_uploads': args.concurrency,
'rounds': args.rounds,
'uploads_ok': sum(results),
'uploads_failed': len(results) - sum(results),
'elapsed_seconds': round(elapsed, 2),
'api_memory_limit_mib': limit,
'idle_memory_mib': {k: round(v, 1) for k, v in sorted(idle.items())},
'peak_memory_mib': {k: round(v, 1) for k, v in sorted(peaks.items())},
'buffering_all_files_would_need_mib': round(args.concurrency * len(data) / 1024 ** 2, 1),
}
text = json.dumps(report, indent=2)
if args.output:
Path(args.output).write_text(text + '\n')
print(text)
check(report['uploads_failed'] == 0, 'some uploads failed')
check(max(peaks.values()) < limit, 'peak memory reached the limit')
if __name__ == '__main__':
run(main)
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
import hashlib
import io
from PIL import Image
from client import Client, arguments, check, run
from stack import SAMPLE, upload, wait_status
EXPECTED = {'thumbnail': ('image/jpeg', 'JPEG'), 'crop': ('image/jpeg', 'JPEG'), 'optimized': ('image/webp', 'WEBP')}
def encode(img, fmt, **kw):
buf = io.BytesIO()
img.save(buf, fmt, **kw)
return buf.getvalue()
def halves(w, h):
img = Image.new('RGB', (w, h), (0, 0, 255))
img.paste((255, 0, 0), (0, 0, w // 2, h))
return img
def process(c, alice, bob, chat, data, content_type='image/png'):
att = upload(c, alice, chat, data, content_type)['json']
ready = wait_status(c, bob, att['id'], ('ready', 'failed'), 60)
check(ready['status'] == 'ready' and ready['error_code'] is None, 'attachment failed: %s' % ready['error_code'])
check(sorted(v['name'] for v in ready['variants']) == sorted(EXPECTED), 'unexpected variant set')
original = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes']
check(original == data and ready['sha256'] == hashlib.sha256(data).hexdigest(), 'original changed')
out = {}
for v in ready['variants']:
r = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + v['name'], actor=bob)
body = r['bytes']
check(r['headers'].get_content_type() == v['content_type'] == EXPECTED[v['name']][0], v['name'] + ' content type')
check(len(body) == v['size_bytes'] and hashlib.sha256(body).hexdigest() == v['sha256'], v['name'] + ' checksum')
img = Image.open(io.BytesIO(body))
check(img.format == EXPECTED[v['name']][1] and img.size == (v['width'], v['height']), v['name'] + ' real size/format')
check('exif' not in img.info, v['name'] + ' keeps EXIF')
img.load()
out[v['name']] = img.convert('RGB')
return att, out
def main():
args = arguments('Thumbnail, crop and optimized variant rules')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
att, v = process(c, alice, bob, chat, SAMPLE)
check(v['thumbnail'].size == (256, 160) and v['crop'].size == (128, 128) and v['optimized'].size == (320, 200), 'fixture sizes')
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=bogus', 400, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=eve)
_, v = process(c, alice, bob, chat, encode(halves(2000, 1000), 'PNG'))
check(v['thumbnail'].size == (256, 128) and v['optimized'].size == (1280, 640) and v['crop'].size == (128, 128), 'large image sizes')
_, v = process(c, alice, bob, chat, encode(halves(100, 50), 'PNG'))
check(v['thumbnail'].size == (100, 50) and v['optimized'].size == (100, 50), 'small image must not be upscaled')
check(v['crop'].size == (128, 128), 'crop must be 128x128')
_, v = process(c, alice, bob, chat, encode(Image.new('RGBA', (300, 300), (0, 0, 0, 0)), 'PNG'))
for name, img in v.items():
check(min(img.getpixel((img.width // 2, img.height // 2))) >= 250, name + ': alpha not composited on white')
exif = Image.Exif()
exif[0x0112] = 6
_, v = process(c, alice, bob, chat, encode(halves(300, 200), 'JPEG', quality=95, exif=exif.tobytes()), 'image/jpeg')
t = v['thumbnail']
check(t.size == (170, 256) and v['optimized'].size == (200, 300), 'EXIF orientation not applied to dimensions')
top, bottom = t.getpixel((85, 20)), t.getpixel((85, 236))
check(top[0] > 200 and top[2] < 60 and bottom[2] > 200 and bottom[0] < 60, 'EXIF rotation direction wrong')
print('PASS: thumbnail/crop/optimized sizes, formats, checksums, no upscale, alpha on white, EXIF orientation, no EXIF in variants')
if __name__ == '__main__':
run(main)
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
import json
import subprocess
import threading
import time
from pathlib import Path
from client import Client, arguments, check, run
from image_gen import png
from stack import SAMPLE, compose, job_row, psql, restore_worker, upload, wait_status
LIMIT_MIB = 768
def sample(stop, state):
while not stop.is_set():
out = compose('exec', '-T', 'worker', 'grep', 'VmRSS', '/proc/1/status', check_rc=False).stdout.split()
if len(out) > 1:
state['rss'] = max(state['rss'], int(out[1]) / 1024)
n = psql("select count(*) from jobs where status = 'processing'")
state['processing'] = max(state['processing'], int(n or 0))
time.sleep(0.2)
def main():
def configure(p):
p.add_argument('--huge', type=int, default=6)
p.add_argument('--small', type=int, default=20)
p.add_argument('--output')
args = arguments('Worker concurrency, memory and time limits', configure)
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
concurrency = int(compose('exec', '-T', 'worker', 'printenv', 'WORKER_CONCURRENCY').stdout.strip())
huge = png(6320, 6320)
state, stop = {'rss': 0, 'processing': 0}, threading.Event()
t = threading.Thread(target=sample, args=(stop, state))
t.start()
started = time.monotonic()
ids = [upload(c, alice, chat, huge)['json']['id'] for _ in range(args.huge)]
ids += [upload(c, alice, chat, SAMPLE)['json']['id'] for _ in range(args.small)]
accepted = time.monotonic() - started
results = [wait_status(c, bob, i, ('ready', 'failed'), 300)['status'] for i in ids]
elapsed = time.monotonic() - started
stop.set()
t.join()
container = compose('ps', '-q', 'worker').stdout.strip()
oom = subprocess.run(['docker', 'inspect', '-f', '{{.RestartCount}} {{.State.OOMKilled}}', container],
capture_output=True, text=True).stdout.split()
compose('stop', 'worker')
slow = upload(c, alice, chat, huge)['json']
compose('up', '-d', '--force-recreate', '--no-deps', 'worker', env={'JOB_TIMEOUT_SECONDS': '1'})
timed = wait_status(c, bob, slow['id'], ('ready', 'failed'), 120)
_, attempts, last_error = job_row(slow['id'])
restore_worker()
report = {
'huge_images': {'count': args.huge, 'pixels': 6320 * 6320, 'bytes': len(huge)},
'small_images': args.small,
'worker_concurrency': concurrency,
'max_processing_jobs_observed': state['processing'],
'all_ready': results.count('ready') == len(results),
'accept_seconds': round(accepted, 2),
'all_ready_seconds': round(elapsed, 1),
'worker_peak_rss_mib': round(state['rss'], 1),
'worker_memory_limit_mib': LIMIT_MIB,
'worker_restarts_oom': oom,
'timeout_case': {'job_timeout_seconds': 1, 'status': timed['status'], 'error_code': timed['error_code'],
'attempts': attempts, 'last_error': last_error},
}
text = json.dumps(report, indent=2)
if args.output:
Path(args.output).write_text(text + '\n')
print(text)
check(report['all_ready'], 'some jobs failed under load')
check(state['processing'] <= concurrency, 'more jobs processing than WORKER_CONCURRENCY')
check(state['rss'] < LIMIT_MIB and oom == ['0', 'false'], 'worker reached memory limit')
check(timed['status'] == 'failed' and timed['error_code'] == 'retry_exhausted' and 'deadline' in last_error,
'timeout must be a bounded transient failure')
print('PASS: bounded worker concurrency, memory below limit, job timeout enforced')
if __name__ == '__main__':
run(main)