lab7: BROKER_URL из окружения, Redis operator для регрессии ACL, исправления тестов, no-new-privileges tempo-init; перенос исправлений lab6
This commit is contained in:
@@ -62,7 +62,7 @@ jobs:
|
||||
stand:
|
||||
name: Стенд — ${{ matrix.part }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 80
|
||||
timeout-minutes: 150
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -97,6 +97,7 @@ jobs:
|
||||
mkdir -p evidence
|
||||
{ nproc; free -m; docker version --format '{{.Server.Version}}'; docker compose version; } > evidence/runner_${{ matrix.part }}.txt
|
||||
docker compose ps -a > evidence/docker_ps_final_${{ matrix.part }}.txt || true
|
||||
for c in $(docker compose ps -aq); do docker inspect -f '{{.Name}} restarts={{.RestartCount}} oom_killed={{.State.OOMKilled}} exit={{.State.ExitCode}}' "$c"; done > evidence/containers_state_${{ matrix.part }}.txt || true
|
||||
docker compose logs --no-color --tail 300 > evidence/compose_logs_${{ matrix.part }}.log 2>&1 || true
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
|
||||
+3
-2
@@ -502,7 +502,7 @@ services:
|
||||
networks: [telemetry]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.50", memory: 512M, pids: 256 }
|
||||
limits: { cpus: "0.50", memory: 1G, pids: 256 }
|
||||
|
||||
tempo-init:
|
||||
image: &tempo-image grafana/tempo:2.6.1
|
||||
@@ -510,6 +510,7 @@ services:
|
||||
entrypoint: ["chown", "10001:10001", "/var/tempo"]
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN]
|
||||
security_opt: [no-new-privileges:true]
|
||||
volumes:
|
||||
- tempo_data:/var/tempo
|
||||
restart: "no"
|
||||
@@ -531,7 +532,7 @@ services:
|
||||
networks: [telemetry]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.50", memory: 512M, pids: 256 }
|
||||
limits: { cpus: "0.50", memory: 1G, pids: 256 }
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.4.0
|
||||
|
||||
@@ -1043,7 +1043,8 @@
|
||||
"mode": "none"
|
||||
}
|
||||
},
|
||||
"min": 0
|
||||
"min": 0,
|
||||
"max": 1
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
|
||||
@@ -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 хранит только текущее
|
||||
@@ -52,7 +55,7 @@ processors:
|
||||
spike_limit_mib: 50
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
send_batch_max_size: 1024
|
||||
timeout: 2s
|
||||
# Защита от утечек на случай ошибки инструментирования: такие ключи не должны
|
||||
# появляться, но если появятся — удаляются до экспорта.
|
||||
@@ -75,7 +78,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
|
||||
@@ -90,7 +93,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
|
||||
|
||||
@@ -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 хранит только текущее
|
||||
@@ -31,7 +34,7 @@ processors:
|
||||
spike_limit_mib: 50
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
send_batch_max_size: 1024
|
||||
timeout: 2s
|
||||
# Защита от утечек на случай ошибки инструментирования: такие ключи не должны
|
||||
# появляться, но если появятся — удаляются до экспорта.
|
||||
@@ -54,7 +57,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
|
||||
@@ -69,7 +72,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
|
||||
|
||||
@@ -20,6 +20,11 @@ distributor:
|
||||
cert_file: /run/secrets/tempo.crt
|
||||
key_file: /run/secrets/tempo.key
|
||||
client_ca_file: /run/secrets/ca.crt
|
||||
# Явный адрес frontend для querier в single-binary: автоматическая настройка после
|
||||
# рестарта Tempo оставляла запросы без ответа (прогон 4, отказ backend).
|
||||
querier:
|
||||
frontend_worker:
|
||||
frontend_address: 127.0.0.1:9095
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
compactor:
|
||||
|
||||
@@ -83,7 +83,7 @@ func Load() Config {
|
||||
S3SecretKey: readSecretFile("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
MaxUploadBytes: int64(getInt("MAX_UPLOAD_BYTES", 10*1024*1024)),
|
||||
MaxImagePixels: int64(getInt("MAX_IMAGE_PIXELS", 40_000_000)),
|
||||
BrokerURL: readSecretFile("BROKER_URL_FILE"),
|
||||
BrokerURL: firstNonEmpty(getEnv("BROKER_URL", ""), readSecretFile("BROKER_URL_FILE")), // lab7: amqps без пароля (EXTERNAL)
|
||||
PipelineVersion: max(1, getInt("PIPELINE_VERSION", 1)),
|
||||
JobMaxAttempts: max(1, getInt("JOB_MAX_ATTEMPTS", 5)),
|
||||
JobTimeout: time.Duration(max(5, getInt("JOB_TIMEOUT_SECONDS", 60))) * time.Second,
|
||||
@@ -174,3 +174,12 @@ func parseDuration(s string) time.Duration {
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func firstNonEmpty(v ...string) string {
|
||||
for _, x := range v {
|
||||
if x != "" {
|
||||
return x
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -159,12 +159,19 @@ def ensure_creds():
|
||||
def write_backend_files(creds):
|
||||
acl = OP / 'redis_users.acl'
|
||||
h = hashlib.sha256(creds['api']['redis_password'].encode()).hexdigest()
|
||||
# Операторская учётка Redis (администрирование, регрессионный тест ACL); приложениям не выдаётся.
|
||||
opf = OP / 'redis_operator_password'
|
||||
if not opf.exists():
|
||||
opf.write_text(rnd.token_hex(24))
|
||||
os.chmod(opf, 0o600)
|
||||
ho = hashlib.sha256(opf.read_text().strip().encode()).hexdigest()
|
||||
# default отключён; api — только свои ключи и нужные команды; healthcheck — только PING.
|
||||
acl.write_text(
|
||||
'user default off\n'
|
||||
'user healthcheck on nopass resetkeys resetchannels -@all +ping +hello +auth\n'
|
||||
'user api on #%s resetchannels ~session:* ~messages:* ~rl:* -@all +@connection '
|
||||
'+get +set +del +ttl +scan +incr +expire +multi +exec +discard +ping\n' % h)
|
||||
'+get +set +del +ttl +scan +incr +expire +multi +exec +discard +ping\n'
|
||||
'user operator on #%s ~* &* +@all\n' % (h, ho))
|
||||
s3 = OP / 's3_users.txt'
|
||||
s3.write_text(''.join('%s %s %s\n' % (s, creds[s]['s3_access_key'], creds[s]['s3_secret_key']) for s in SERVICES))
|
||||
for p in (acl, s3):
|
||||
|
||||
@@ -31,7 +31,7 @@ def row(title):
|
||||
y += 1
|
||||
|
||||
|
||||
def ts(title, targets, unit, x, w=8, h=8, desc='', stack=False, minv=None):
|
||||
def ts(title, targets, unit, x, w=8, h=8, desc='', stack=False, minv=None, maxv=None):
|
||||
p = {'type': 'timeseries', 'title': title, 'id': nid(), 'datasource': PROM, 'description': desc,
|
||||
'gridPos': {'h': h, 'w': w, 'x': x, 'y': y},
|
||||
'fieldConfig': {'defaults': {'unit': unit, 'custom': {'fillOpacity': 10, 'showPoints': 'never',
|
||||
@@ -42,6 +42,8 @@ def ts(title, targets, unit, x, w=8, h=8, desc='', stack=False, minv=None):
|
||||
'exemplar': True} for i, (e, l) in enumerate(targets)]}
|
||||
if minv is not None:
|
||||
p['fieldConfig']['defaults']['min'] = minv
|
||||
if maxv is not None:
|
||||
p['fieldConfig']['defaults']['max'] = maxv
|
||||
panels.append(p)
|
||||
|
||||
|
||||
@@ -118,7 +120,7 @@ ts('RabbitMQ: сообщения в очередях',
|
||||
'none', 16)
|
||||
y += 8
|
||||
ts('Saturation worker (busy / capacity)',
|
||||
[('sum(messenger_worker_busy) / sum(messenger_worker_capacity)', 'занято слотов')], 'percentunit', 0, minv=0)
|
||||
[('sum(messenger_worker_busy) / sum(messenger_worker_capacity)', 'занято слотов')], 'percentunit', 0, minv=0, maxv=1)
|
||||
ts('Publish outbox → broker (confirm) p95',
|
||||
[(q('messenger_outbox_publish_duration_seconds_bucket')(0.95), 'p95'),
|
||||
('sum(rate(messenger_outbox_published_total[$__rate_interval]))', 'сообщений/с')], 's', 8)
|
||||
|
||||
@@ -174,6 +174,8 @@ def scenario_db_gap(c):
|
||||
def scenario_security(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, fixture('small.png'))['json']
|
||||
# С lab5 worker переносит оригинал staging s/ → o/: ключ берём после ready.
|
||||
wait_status(c, alice, att['id'], ('ready',))
|
||||
key = object_key(att['id'])
|
||||
url = 'http://s3:9000/%s/%s' % (BUCKET, key)
|
||||
# Анонимно изнутри сети стенда (из контейнера API): объект и листинг закрыты.
|
||||
|
||||
@@ -89,7 +89,7 @@ class Uploader:
|
||||
while not self.stop_ev.is_set():
|
||||
try:
|
||||
r = self.c.call('POST', '/api/v1/chats/%s/attachments?filename=u.png' % self.chat['id'], 202,
|
||||
actor=self.actor, raw=SAMPLE, headers={'Content-Type': 'image/png'})
|
||||
actor=self.actor, raw=SAMPLE, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
self.ids.append((time.time(), r['json']['id']))
|
||||
except Failure:
|
||||
self.errors += 1
|
||||
@@ -156,7 +156,7 @@ def main():
|
||||
|
||||
# первое задание, принятое после реакции, — когда стало ready (восстановление обработки)
|
||||
probe_att = c.call('POST', '/api/v1/chats/%s/attachments?filename=after.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
|
||||
headers={'Content-Type': 'image/png'})['json']
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
meta = wait_status(c, bob, probe_att['id'], ('ready', 'failed'), timeout=240)
|
||||
res['processing_restored_seconds_after_response'] = round(time.time() - t_done, 1)
|
||||
check(meta['status'] == 'ready', 'worker did not recover with the new identity')
|
||||
|
||||
@@ -114,7 +114,7 @@ def scenario_signals(c):
|
||||
spans, _ = o.tempo_trace(tid)
|
||||
server = [s for s in spans if s['kind'] in ('SPAN_KIND_SERVER', 2, '2') or s['name'].startswith('POST /api')]
|
||||
check(server, 'no server span')
|
||||
logs = o.wait_until(lambda: o.loki('{service_name="messenger-api"} | trace_id="%s"' % tid, t0), 60)
|
||||
logs = o.wait_until(lambda: o.loki('{service_name="messenger-api"} | trace_id="%s"' % tid, t0), 120)
|
||||
check(logs, 'no API log with trace_id ' + tid)
|
||||
log_line = logs[0][1]
|
||||
res['request'] = {'request_id': rid_msg, 'trace_id': tid, 'spans': tree(spans)[:12],
|
||||
@@ -141,7 +141,7 @@ def scenario_signals(c):
|
||||
db_in_worker = sorted({s['name'] for s in spans2 if s['service'] == 'messenger-worker' and s['name'] not in
|
||||
('attachment.process process', 'image.decode', 'image.variants') and not s['name'].startswith('S3')})
|
||||
check(all(links.values()), 'broken causal chain: %s' % links)
|
||||
wlogs = o.wait_until(lambda: o.loki('{service_name="messenger-worker"} | trace_id="%s"' % tid2, t0), 60)
|
||||
wlogs = o.wait_until(lambda: o.loki('{service_name="messenger-worker"} | trace_id="%s"' % tid2, t0), 120)
|
||||
check(wlogs, 'no worker log with the upload trace_id')
|
||||
res['upload'] = {'request_id': rid_up, 'trace_id': tid2, 'services': services, 'links': links,
|
||||
'span_count': len(spans2), 'worker_db_spans': db_in_worker[:10], 'tree': tree(spans2)[:40],
|
||||
@@ -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()
|
||||
|
||||
@@ -25,6 +25,18 @@ def _auth():
|
||||
|
||||
|
||||
def grafana(path, params=None, method='GET', body=None, timeout=30):
|
||||
"""Запрос к Grafana; 502/503/504 (backend перезапускается) — повтор до ~60 s."""
|
||||
import urllib.error
|
||||
for attempt in range(12):
|
||||
try:
|
||||
return _grafana(path, params, method, body, timeout)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code not in (502, 503, 504) or attempt == 11:
|
||||
raise
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def _grafana(path, params=None, method='GET', body=None, timeout=30):
|
||||
url = GRAFANA + path
|
||||
if params:
|
||||
url += ('&' if '?' in url else '?') + urllib.parse.urlencode(params)
|
||||
|
||||
@@ -23,7 +23,11 @@ WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, ' ' * 8)
|
||||
|
||||
|
||||
def redis_cli(*args):
|
||||
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
|
||||
# Lab7: Redis только по TLS, пользователь default выключен — операторская учётка
|
||||
# (пароль из secrets/operator, передаётся через окружение exec, не аргументом).
|
||||
pw = (ROOT / 'secrets' / 'operator' / 'redis_operator_password').read_text().strip()
|
||||
r = subprocess.run(['docker', 'compose', 'exec', '-T', '-e', 'REDISCLI_AUTH=' + pw, 'redis', 'redis-cli', '--tls',
|
||||
'--cacert', '/run/secrets/ca.crt', '-h', 'redis', '--user', 'operator', '--no-auth-warning', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=30)
|
||||
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
|
||||
return r.stdout.strip()
|
||||
@@ -35,7 +39,7 @@ def visibility_case(c, alice, bob, chat, denied):
|
||||
# Прогреваем кэш на обеих репликах.
|
||||
for _ in range(4):
|
||||
c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
|
||||
redis_cli('ACL', 'SETUSER', 'api', *('-' + cmd for cmd in denied)) # lab7: пользователь API — api
|
||||
try:
|
||||
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
|
||||
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
|
||||
@@ -47,8 +51,8 @@ def visibility_case(c, alice, bob, chat, denied):
|
||||
# встать раньше старых, поэтому проверяем наличие, а не префикс.
|
||||
check(set(before) <= set(ids), 'previously confirmed messages missing')
|
||||
finally:
|
||||
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
|
||||
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
|
||||
# Исходные права api — из ACL-файла оператора (там же hash пароля).
|
||||
redis_cli('ACL', 'LOAD')
|
||||
return len(before) + 1
|
||||
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ def scenario_mtls(c):
|
||||
'trusted_ca_cn_lb': probe('amqp', '-cert', p + 'lb.crt', '-key', p + 'lb.key'),
|
||||
'worker': probe('amqp', '-cert', p + 'worker.crt', '-key', p + 'worker.key'),
|
||||
'relay': probe('amqp', '-cert', p + 'relay.crt', '-key', p + 'relay.key'),
|
||||
'plaintext_5672': probe('plain', '-addr', 'rabbitmq:5672', '-send', 'AMQP\x00\x00\x09\x01'),
|
||||
'plaintext_5672': probe('plain', '-addr', 'rabbitmq:5672', '-send', 'AMQP'),
|
||||
}
|
||||
for k in ('foreign_ca', 'trusted_ca_cn_attacker', 'trusted_ca_cn_lb'):
|
||||
check(denied(broker[k].get('connect')), 'broker %s not rejected: %s' % (k, broker[k]))
|
||||
@@ -190,7 +190,7 @@ def scenario_mtls(c):
|
||||
def scenario_acl(c):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=a.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
|
||||
headers={'Content-Type': 'image/png'})['json']
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
res = {}
|
||||
res['outsider_metadata'] = c.call('GET', '/api/v1/attachments/' + att['id'], (404,), actor=eve)['status']
|
||||
@@ -350,7 +350,7 @@ def scenario_rotation(c):
|
||||
time.sleep(35) # SECRETS_REFRESH 30 s
|
||||
# Старые соединения закрываются (как при отзыве); новые открываются с новым паролем
|
||||
psql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename = 'app_api'")
|
||||
time.sleep(5)
|
||||
time.sleep(35) # pgx health check (30 s) выбрасывает разорванные соединения
|
||||
res['db_old_password'] = probe('db', '-user', 'app_api', '-stdin', stdin=old_pw).get('connect')
|
||||
check(denied(res['db_old_password']), 'old db password still works')
|
||||
res['api_after_db_rotation'] = c.call('GET', '/api/v1/chats', actor=alice)['status']
|
||||
@@ -358,7 +358,7 @@ def scenario_rotation(c):
|
||||
bootstrap('rotate-s3', 'worker')
|
||||
time.sleep(35)
|
||||
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=r.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
|
||||
headers={'Content-Type': 'image/png'})['json']
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
res['upload_after_s3_rotation'] = wait_status(c, bob, att['id'], ('ready', 'failed'), timeout=150)['status']
|
||||
check(res['upload_after_s3_rotation'] == 'ready', 'worker did not pick rotated S3 key')
|
||||
# 3) leaf API: перевыпуск на месте, без рестарта; LB видит новый serial
|
||||
@@ -409,14 +409,14 @@ def scenario_lifecycle(c):
|
||||
bootstrap('seal')
|
||||
t_seal = time.time()
|
||||
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=s.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
|
||||
headers={'Content-Type': 'image/png'})['json']
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
res['upload_while_sealed'] = wait_status(c, bob, att['id'], ('ready', 'failed'), timeout=120)['status']
|
||||
compose('restart', 'worker')
|
||||
time.sleep(25)
|
||||
wlogs = compose('logs', '--no-color', '--since', '30s', 'worker').stdout
|
||||
res['worker_restart_while_sealed'] = 'openbao not ready' in wlogs or 'sealed' in wlogs
|
||||
att2 = c.call('POST', '/api/v1/chats/%s/attachments?filename=s2.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
|
||||
headers={'Content-Type': 'image/png'})['json']
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
time.sleep(5)
|
||||
res['upload_accepted_while_worker_blocked'] = att2['status']
|
||||
bootstrap('unseal')
|
||||
|
||||
Reference in New Issue
Block a user