feat(security): add scoped identities, TLS boundaries and OpenBao bootstrap
This commit is contained in:
@@ -0,0 +1,351 @@
|
||||
"""Explicit operator init/unseal/configure; no unseal material enters containers."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from cryptography import x509
|
||||
|
||||
from scripts.bootstrap_security import (
|
||||
OPERATOR,
|
||||
ROLES,
|
||||
ROOT,
|
||||
TRUST,
|
||||
ca,
|
||||
public,
|
||||
sign_intermediate,
|
||||
write_private,
|
||||
)
|
||||
|
||||
|
||||
class Operator:
|
||||
def __init__(self):
|
||||
context = ssl.create_default_context(cafile=TRUST / "ca.pem")
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
context.load_cert_chain(
|
||||
OPERATOR / "client/cert.pem", OPERATOR / "client/key.pem"
|
||||
)
|
||||
self.http = httpx.Client(
|
||||
base_url="https://localhost:"
|
||||
+ os.getenv("BAO_PORT", "8207")
|
||||
+ "/v1/",
|
||||
verify=context,
|
||||
trust_env=False,
|
||||
timeout=10,
|
||||
)
|
||||
self.token = None
|
||||
|
||||
def close(self):
|
||||
self.http.close()
|
||||
|
||||
def call(self, method, path, payload=None, *, token=None):
|
||||
response = self.http.request(
|
||||
method,
|
||||
path,
|
||||
json=payload,
|
||||
headers={"X-Vault-Token": token} if token else {},
|
||||
)
|
||||
if response.status_code >= 300:
|
||||
raise RuntimeError(
|
||||
"Operator request denied/unavailable: "
|
||||
+ path
|
||||
+ " status "
|
||||
+ str(response.status_code)
|
||||
)
|
||||
return response.json() if response.content else {}
|
||||
|
||||
def init(self):
|
||||
if self.call("GET", "sys/init")["initialized"]:
|
||||
return
|
||||
result = self.call(
|
||||
"POST", "sys/init", {"secret_shares": 3, "secret_threshold": 2}
|
||||
)
|
||||
for index, key in enumerate(result["keys_base64"]):
|
||||
write_private(
|
||||
OPERATOR / ("unseal-" + str(index + 1) + ".json"),
|
||||
json.dumps({"key": key}) + "\n",
|
||||
)
|
||||
write_private(OPERATOR / "bootstrap-root-token", result["root_token"])
|
||||
|
||||
def unseal(self):
|
||||
state = self.call("GET", "sys/seal-status")
|
||||
if not state["sealed"]:
|
||||
return
|
||||
for index in [1, 2]:
|
||||
share = json.loads(
|
||||
(OPERATOR / ("unseal-" + str(index) + ".json")).read_text()
|
||||
)
|
||||
state = self.call("POST", "sys/unseal", {"key": share["key"]})
|
||||
if not state["sealed"]:
|
||||
return
|
||||
raise RuntimeError("Unseal threshold not reached")
|
||||
|
||||
def authenticate(self):
|
||||
cached = OPERATOR / "operator-token.json"
|
||||
if cached.exists():
|
||||
data = json.loads(cached.read_text())
|
||||
if data["expires_at"] > time.time() + 30:
|
||||
self.token = data["token"]
|
||||
return self.token
|
||||
result = self.call("POST", "auth/cert/login", {})["auth"]
|
||||
self.token = result["client_token"]
|
||||
write_private(
|
||||
cached,
|
||||
json.dumps(
|
||||
{
|
||||
"token": self.token,
|
||||
"expires_at": time.time() + result["lease_duration"],
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
return self.token
|
||||
|
||||
def authorized(self, method, path, payload=None):
|
||||
return self.call(
|
||||
method, path, payload, token=self.token or self.authenticate()
|
||||
)
|
||||
|
||||
def configure(self):
|
||||
marker = OPERATOR / "configured.json"
|
||||
if marker.exists():
|
||||
self.authenticate()
|
||||
self.authorized("GET", "auth/token/lookup-self")
|
||||
return
|
||||
token = (OPERATOR / "bootstrap-root-token").read_text().strip()
|
||||
|
||||
def root(method, path, payload=None):
|
||||
return self.call(method, path, payload, token=token)
|
||||
|
||||
mounts = root("GET", "sys/mounts")
|
||||
mounts = mounts.get("data", mounts)
|
||||
if "secret/" not in mounts:
|
||||
root(
|
||||
"POST",
|
||||
"sys/mounts/secret",
|
||||
{"type": "kv", "options": {"version": "2"}},
|
||||
)
|
||||
if "pki/" not in mounts:
|
||||
root(
|
||||
"POST",
|
||||
"sys/mounts/pki",
|
||||
{"type": "pki", "config": {"max_lease_ttl": "720h"}},
|
||||
)
|
||||
auth = root("GET", "sys/auth")
|
||||
auth = auth.get("data", auth)
|
||||
if "cert/" not in auth:
|
||||
root("POST", "sys/auth/cert", {"type": "cert"})
|
||||
issuer_marker = OPERATOR / "initial-issuer.json"
|
||||
if not issuer_marker.exists():
|
||||
csr = root(
|
||||
"POST",
|
||||
"pki/intermediate/generate/internal",
|
||||
{
|
||||
"common_name": "Messenger service intermediate",
|
||||
"key_type": "ec",
|
||||
"key_bits": 256,
|
||||
},
|
||||
)["data"]["csr"]
|
||||
key, cert = ca()
|
||||
intermediate = sign_intermediate(
|
||||
key, cert, x509.load_pem_x509_csr(csr.encode())
|
||||
)
|
||||
imported = root(
|
||||
"POST",
|
||||
"pki/intermediate/set-signed",
|
||||
{
|
||||
"certificate": (
|
||||
public(intermediate) + public(cert)
|
||||
).decode()
|
||||
},
|
||||
)
|
||||
issuers = imported["data"]["imported_issuers"]
|
||||
selected = None
|
||||
for issuer in issuers:
|
||||
details = root("GET", "pki/issuer/" + issuer)["data"]
|
||||
loaded = x509.load_pem_x509_certificate(
|
||||
details["certificate"].encode()
|
||||
)
|
||||
if loaded.serial_number == intermediate.serial_number:
|
||||
selected = issuer
|
||||
assert selected, "Imported signing intermediate not found"
|
||||
root(
|
||||
"POST",
|
||||
"pki/config/issuers",
|
||||
{"default": selected, "default_follows_latest_issuer": False},
|
||||
)
|
||||
write_private(
|
||||
issuer_marker,
|
||||
json.dumps(
|
||||
{
|
||||
"configured": True,
|
||||
"imported_issuers": imported.get("data", {}).get(
|
||||
"imported_issuers", []
|
||||
),
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
_, cert = ca()
|
||||
material = json.loads((OPERATOR / "service-secrets.json").read_text())
|
||||
for role, cfg in ROLES.items():
|
||||
policy = (
|
||||
ROOT / "infra/openbao/policies" / (role + ".hcl")
|
||||
).read_text()
|
||||
if cfg["kv"]:
|
||||
root(
|
||||
"POST",
|
||||
"secret/data/" + role,
|
||||
{"data": material["services"][role]["values"]},
|
||||
)
|
||||
root(
|
||||
"PUT", "sys/policies/acl/messenger-" + role, {"policy": policy}
|
||||
)
|
||||
root(
|
||||
"POST",
|
||||
"pki/roles/" + role,
|
||||
{
|
||||
"allowed_domains": cfg["dns"],
|
||||
"allow_bare_domains": True,
|
||||
"allow_subdomains": False,
|
||||
"allow_wildcard_certificates": False,
|
||||
"allow_any_name": False,
|
||||
"allow_localhost": "localhost" in cfg["dns"],
|
||||
"allow_ip_sans": bool(cfg.get("ip")),
|
||||
"allowed_uri_sans": ["spiffe://messenger/" + role],
|
||||
"enforce_hostnames": True,
|
||||
"key_type": "ec",
|
||||
"key_bits": 256,
|
||||
"server_flag": True,
|
||||
"client_flag": True,
|
||||
"ttl": "120s",
|
||||
"max_ttl": "120s",
|
||||
"issuer_ref": "default",
|
||||
},
|
||||
)
|
||||
root(
|
||||
"POST",
|
||||
"auth/cert/certs/" + role + "-v1",
|
||||
{
|
||||
"display_name": role,
|
||||
"certificate": public(cert).decode(),
|
||||
"allowed_common_names": [role],
|
||||
"allowed_uri_sans": ["spiffe://messenger/" + role],
|
||||
"token_policies": ["messenger-" + role],
|
||||
"token_ttl": "120s",
|
||||
"token_max_ttl": "600s",
|
||||
"token_no_default_policy": True,
|
||||
},
|
||||
)
|
||||
operator_policy = (
|
||||
ROOT / "infra/openbao/policies/operator.hcl"
|
||||
).read_text()
|
||||
root(
|
||||
"PUT",
|
||||
"sys/policies/acl/messenger-operator",
|
||||
{"policy": operator_policy},
|
||||
)
|
||||
root(
|
||||
"POST",
|
||||
"auth/cert/certs/operator-v1",
|
||||
{
|
||||
"display_name": "operator",
|
||||
"certificate": public(cert).decode(),
|
||||
"allowed_common_names": ["operator"],
|
||||
"allowed_uri_sans": ["spiffe://messenger/operator"],
|
||||
"token_policies": ["messenger-operator"],
|
||||
"token_ttl": "900s",
|
||||
"token_max_ttl": "3600s",
|
||||
"token_no_default_policy": True,
|
||||
},
|
||||
)
|
||||
audit = root("GET", "sys/audit")
|
||||
audit = audit.get("data", audit)
|
||||
if "file/" not in audit:
|
||||
root(
|
||||
"PUT",
|
||||
"sys/audit/file",
|
||||
{
|
||||
"type": "file",
|
||||
"options": {
|
||||
"file_path": "/data/audit/audit.log",
|
||||
"mode": "0600",
|
||||
},
|
||||
},
|
||||
)
|
||||
created = root(
|
||||
"POST",
|
||||
"auth/token/create-orphan",
|
||||
{
|
||||
"policies": ["messenger-operator"],
|
||||
"ttl": "900s",
|
||||
"renewable": True,
|
||||
"no_default_policy": True,
|
||||
},
|
||||
)["auth"]
|
||||
write_private(
|
||||
OPERATOR / "operator-token.json",
|
||||
json.dumps(
|
||||
{
|
||||
"token": created["client_token"],
|
||||
"expires_at": time.time() + created["lease_duration"],
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
root("POST", "auth/token/revoke-self", {})
|
||||
write_private(
|
||||
marker,
|
||||
json.dumps({"configured": True, "root_token_revoked": True})
|
||||
+ "\n",
|
||||
)
|
||||
(OPERATOR / "bootstrap-root-token").unlink()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"action", choices=["init", "unseal", "configure", "status", "seal"]
|
||||
)
|
||||
args = parser.parse_args()
|
||||
operator = Operator()
|
||||
try:
|
||||
if args.action == "init":
|
||||
operator.init()
|
||||
operator.unseal()
|
||||
operator.configure()
|
||||
elif args.action == "unseal":
|
||||
operator.unseal()
|
||||
elif args.action == "configure":
|
||||
operator.configure()
|
||||
elif args.action == "seal":
|
||||
operator.authorized("POST", "sys/seal", {})
|
||||
else:
|
||||
state = operator.call("GET", "sys/seal-status")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
k: state[k]
|
||||
for k in [
|
||||
"initialized",
|
||||
"sealed",
|
||||
"version",
|
||||
"storage_type",
|
||||
]
|
||||
if k in state
|
||||
}
|
||||
)
|
||||
)
|
||||
if args.action != "status":
|
||||
print(
|
||||
"Operator action completed; no tokens or unseal shares printed"
|
||||
)
|
||||
finally:
|
||||
operator.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Создаёт только отсутствующие локальные файлы; секреты не печатает."""
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def create(path, value):
|
||||
try:
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
|
||||
except FileExistsError:
|
||||
return
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
stream.write(value + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
directory = ROOT / "secrets"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
pg = directory / "postgres_password"
|
||||
cache = directory / "cache_password"
|
||||
create(pg, secrets.token_urlsafe(32))
|
||||
create(cache, secrets.token_urlsafe(32))
|
||||
create(
|
||||
directory / "database_url",
|
||||
"postgresql://messenger:"
|
||||
+ pg.read_text().strip()
|
||||
+ "@postgres:5432/messenger",
|
||||
)
|
||||
create(
|
||||
directory / "cache_url",
|
||||
"redis://:" + cache.read_text().strip() + "@cache:6379/0",
|
||||
)
|
||||
create(
|
||||
directory / "valkey.conf",
|
||||
"bind 0.0.0.0\nprotected-mode yes\nport 6379\nmaxmemory 64mb\n"
|
||||
'maxmemory-policy allkeys-lru\nsave ""\nappendonly no\nrequirepass '
|
||||
+ cache.read_text().strip(),
|
||||
)
|
||||
create(directory / "s3_root_user", secrets.token_hex(10))
|
||||
create(directory / "s3_root_password", secrets.token_urlsafe(32))
|
||||
create(directory / "s3_access_key", secrets.token_hex(10))
|
||||
create(directory / "s3_secret_key", secrets.token_urlsafe(32))
|
||||
create(directory / "grafana_password", secrets.token_urlsafe(32))
|
||||
create(directory / "broker_password", secrets.token_urlsafe(32))
|
||||
create(
|
||||
directory / "broker_url",
|
||||
"redis://:"
|
||||
+ (directory / "broker_password").read_text().strip()
|
||||
+ "@broker:6379/0",
|
||||
)
|
||||
create(
|
||||
directory / "broker.conf",
|
||||
"bind 0.0.0.0\nprotected-mode yes\nport 6379\nappendonly yes\nappendfsync always\nmaxmemory 192mb\nmaxmemory-policy noeviction\ndir /data\nrequirepass "
|
||||
+ (directory / "broker_password").read_text().strip(),
|
||||
)
|
||||
create(ROOT / ".env", (ROOT / ".env.example").read_text().rstrip())
|
||||
print("Local configuration ready; existing files preserved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,416 @@
|
||||
"""Operator-only offline trust/bootstrap generation; never prints key material."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OPERATOR = ROOT / "operator"
|
||||
SECRET = ROOT / "secrets"
|
||||
TRUST = ROOT / "trust"
|
||||
ROLES = {
|
||||
"openbao": {
|
||||
"dns": ["openbao", "localhost"],
|
||||
"ip": ["127.0.0.1"],
|
||||
"uid": 1000,
|
||||
"kv": False,
|
||||
},
|
||||
"api": {"dns": ["api", "localhost"], "uid": 10001, "kv": True},
|
||||
"worker": {"dns": ["worker"], "uid": 10001, "kv": True},
|
||||
"relay": {"dns": ["relay"], "uid": 10001, "kv": True},
|
||||
"observer": {"dns": ["observer"], "uid": 10001, "kv": True},
|
||||
"reconciler": {"dns": ["reconciler"], "uid": 10001, "kv": True},
|
||||
"migrate": {"dns": ["migrate"], "uid": 10001, "kv": True},
|
||||
"lb": {
|
||||
"dns": ["lb", "localhost"],
|
||||
"ip": ["127.0.0.1"],
|
||||
"uid": 99,
|
||||
"kv": False,
|
||||
},
|
||||
"postgres": {"dns": ["postgres"], "uid": 10001, "kv": False},
|
||||
"s3": {
|
||||
"dns": ["s3", "localhost"],
|
||||
"ip": ["127.0.0.1"],
|
||||
"uid": 10001,
|
||||
"kv": False,
|
||||
},
|
||||
"broker": {"dns": ["broker"], "uid": 10001, "kv": False},
|
||||
"cache": {"dns": ["cache"], "uid": 10001, "kv": False},
|
||||
"otel": {"dns": ["otel"], "uid": 10001, "kv": False},
|
||||
"prometheus": {"dns": ["prometheus"], "uid": 65534, "kv": False},
|
||||
"loki": {"dns": ["loki"], "uid": 10001, "kv": False},
|
||||
"tempo": {"dns": ["tempo"], "uid": 10001, "kv": False},
|
||||
"grafana": {
|
||||
"dns": ["grafana", "localhost"],
|
||||
"ip": ["127.0.0.1"],
|
||||
"uid": 472,
|
||||
"kv": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_private(path, content, *, mode=0o600):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
raw = content.encode() if isinstance(content, str) else content
|
||||
temporary = path.with_name(path.name + ".new")
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
||||
try:
|
||||
os.fchmod(fd, mode)
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
stream.write(raw)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except BaseException:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def key_bytes(key):
|
||||
return key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
|
||||
|
||||
def public(cert):
|
||||
return cert.public_bytes(serialization.Encoding.PEM)
|
||||
|
||||
|
||||
def make_root():
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name(
|
||||
[
|
||||
x509.NameAttribute(
|
||||
NameOID.COMMON_NAME,
|
||||
"Messenger lab root " + secrets.token_hex(4),
|
||||
)
|
||||
]
|
||||
)
|
||||
now = datetime.now(UTC)
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=1))
|
||||
.not_valid_after(now + timedelta(days=365))
|
||||
.add_extension(
|
||||
x509.BasicConstraints(ca=True, path_length=1), critical=True
|
||||
)
|
||||
.add_extension(
|
||||
x509.KeyUsage(
|
||||
digital_signature=True,
|
||||
content_commitment=False,
|
||||
key_encipherment=False,
|
||||
data_encipherment=False,
|
||||
key_agreement=False,
|
||||
key_cert_sign=True,
|
||||
crl_sign=True,
|
||||
encipher_only=False,
|
||||
decipher_only=False,
|
||||
),
|
||||
critical=True,
|
||||
)
|
||||
.add_extension(
|
||||
x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
.sign(key, hashes.SHA256())
|
||||
)
|
||||
return key, cert
|
||||
|
||||
|
||||
def sign_leaf(ca_key, ca_cert, role, dns, ips=(), *, seconds=1800):
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
now = datetime.now(UTC)
|
||||
names = [x509.DNSName(name) for name in dns]
|
||||
names += [x509.IPAddress(ipaddress.ip_address(ip)) for ip in ips]
|
||||
names += [x509.UniformResourceIdentifier("spiffe://messenger/" + role)]
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(
|
||||
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, role)])
|
||||
)
|
||||
.issuer_name(ca_cert.subject)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(seconds=30))
|
||||
.not_valid_after(now + timedelta(seconds=seconds))
|
||||
.add_extension(
|
||||
x509.BasicConstraints(ca=False, path_length=None), critical=True
|
||||
)
|
||||
.add_extension(x509.SubjectAlternativeName(names), critical=False)
|
||||
.add_extension(
|
||||
x509.ExtendedKeyUsage(
|
||||
[
|
||||
ExtendedKeyUsageOID.CLIENT_AUTH,
|
||||
ExtendedKeyUsageOID.SERVER_AUTH,
|
||||
]
|
||||
),
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(
|
||||
x509.KeyUsage(
|
||||
digital_signature=True,
|
||||
content_commitment=False,
|
||||
key_encipherment=False,
|
||||
data_encipherment=False,
|
||||
key_agreement=False,
|
||||
key_cert_sign=False,
|
||||
crl_sign=False,
|
||||
encipher_only=False,
|
||||
decipher_only=False,
|
||||
),
|
||||
critical=True,
|
||||
)
|
||||
.add_extension(
|
||||
x509.AuthorityKeyIdentifier.from_issuer_public_key(
|
||||
ca_key.public_key()
|
||||
),
|
||||
critical=False,
|
||||
)
|
||||
.sign(ca_key, hashes.SHA256())
|
||||
)
|
||||
return key, cert
|
||||
|
||||
|
||||
def sign_intermediate(ca_key, ca_cert, csr):
|
||||
now = datetime.now(UTC)
|
||||
assert csr.is_signature_valid
|
||||
return (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(csr.subject)
|
||||
.issuer_name(ca_cert.subject)
|
||||
.public_key(csr.public_key())
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(seconds=30))
|
||||
.not_valid_after(now + timedelta(days=30))
|
||||
.add_extension(
|
||||
x509.BasicConstraints(ca=True, path_length=0), critical=True
|
||||
)
|
||||
.add_extension(
|
||||
x509.KeyUsage(
|
||||
digital_signature=True,
|
||||
content_commitment=False,
|
||||
key_encipherment=False,
|
||||
data_encipherment=False,
|
||||
key_agreement=False,
|
||||
key_cert_sign=True,
|
||||
crl_sign=True,
|
||||
encipher_only=False,
|
||||
decipher_only=False,
|
||||
),
|
||||
critical=True,
|
||||
)
|
||||
.add_extension(
|
||||
x509.SubjectKeyIdentifier.from_public_key(csr.public_key()),
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(
|
||||
x509.AuthorityKeyIdentifier.from_issuer_public_key(
|
||||
ca_key.public_key()
|
||||
),
|
||||
critical=False,
|
||||
)
|
||||
.sign(ca_key, hashes.SHA256())
|
||||
)
|
||||
|
||||
|
||||
def ca():
|
||||
return (
|
||||
serialization.load_pem_private_key(
|
||||
(OPERATOR / "ca-key.pem").read_bytes(), password=None
|
||||
),
|
||||
x509.load_pem_x509_certificate((OPERATOR / "ca.pem").read_bytes()),
|
||||
)
|
||||
|
||||
|
||||
def generate():
|
||||
for directory in [OPERATOR, SECRET]:
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
directory.chmod(0o700)
|
||||
TRUST.mkdir(mode=0o755, exist_ok=True)
|
||||
if not (OPERATOR / "ca-key.pem").exists():
|
||||
key, cert = make_root()
|
||||
write_private(OPERATOR / "ca-key.pem", key_bytes(key))
|
||||
write_private(OPERATOR / "ca.pem", public(cert))
|
||||
key, cert = ca()
|
||||
if not (TRUST / "ca.pem").exists():
|
||||
write_private(TRUST / "ca.pem", public(cert), mode=0o644)
|
||||
write_private(TRUST / "revoked.json", "{}\n", mode=0o644)
|
||||
for role, cfg in {
|
||||
**ROLES,
|
||||
"openbao": {"dns": ["openbao", "localhost"], "ip": ["127.0.0.1"]},
|
||||
"operator": {"dns": ["operator"]},
|
||||
}.items():
|
||||
directory = (
|
||||
(OPERATOR / "client")
|
||||
if role == "operator"
|
||||
else SECRET / "bootstrap" / role
|
||||
)
|
||||
renew_operator = (
|
||||
role == "operator"
|
||||
and (directory / "cert.pem").exists()
|
||||
and x509.load_pem_x509_certificate(
|
||||
(directory / "cert.pem").read_bytes()
|
||||
).not_valid_after_utc
|
||||
< datetime.now(UTC) + timedelta(hours=1)
|
||||
)
|
||||
if not (directory / "key.pem").exists() or renew_operator:
|
||||
leaf_key, leaf = sign_leaf(
|
||||
key,
|
||||
cert,
|
||||
role,
|
||||
cfg["dns"],
|
||||
cfg.get("ip", ()),
|
||||
seconds=86400 if role in {"operator", "openbao"} else 1800,
|
||||
)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
directory.chmod(0o700 if role == "operator" else 0o755)
|
||||
mode = 0o600 if role == "operator" else 0o644
|
||||
write_private(
|
||||
directory / "key.pem", key_bytes(leaf_key), mode=mode
|
||||
)
|
||||
write_private(
|
||||
directory / "cert.pem", public(leaf) + public(cert), mode=mode
|
||||
)
|
||||
write_private(
|
||||
directory / "bundle.pem",
|
||||
public(leaf) + public(cert) + key_bytes(leaf_key),
|
||||
mode=mode,
|
||||
)
|
||||
path = OPERATOR / "service-secrets.json"
|
||||
if path.exists():
|
||||
raw = json.loads(path.read_text())
|
||||
else:
|
||||
raw = {
|
||||
name: secrets.token_urlsafe(32)
|
||||
for name in [
|
||||
"postgres_password",
|
||||
"s3_root_password",
|
||||
"broker_admin",
|
||||
"cache_admin",
|
||||
"cache_api",
|
||||
"grafana_password",
|
||||
]
|
||||
}
|
||||
raw["s3_root_user"] = "operator-" + secrets.token_hex(12)
|
||||
raw["services"] = {}
|
||||
for role in [
|
||||
"api",
|
||||
"worker",
|
||||
"relay",
|
||||
"observer",
|
||||
"reconciler",
|
||||
"migrate",
|
||||
]:
|
||||
pwd = secrets.token_urlsafe(32)
|
||||
values = {
|
||||
"DATABASE_URL": "postgresql://"
|
||||
+ ("messenger" if role == "migrate" else "svc_" + role)
|
||||
+ ":"
|
||||
+ quote(
|
||||
raw["postgres_password"] if role == "migrate" else pwd,
|
||||
safe="",
|
||||
)
|
||||
+ "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/run/identity/current/key.pem"
|
||||
}
|
||||
service = {"database_password": pwd, "values": values}
|
||||
if role == "api":
|
||||
values["CACHE_URL"] = (
|
||||
"rediss://api:" + raw["cache_api"] + "@cache:6380/0"
|
||||
)
|
||||
if role in {"relay", "worker"}:
|
||||
service["broker_password"] = secrets.token_urlsafe(32)
|
||||
values["BROKER_URL"] = (
|
||||
"rediss://"
|
||||
+ role
|
||||
+ ":"
|
||||
+ service["broker_password"]
|
||||
+ "@broker:6380/0"
|
||||
)
|
||||
if role in {"api", "worker", "reconciler"}:
|
||||
values.update(
|
||||
S3_ACCESS_KEY=role + "-" + secrets.token_hex(12),
|
||||
S3_SECRET_KEY=secrets.token_urlsafe(32),
|
||||
)
|
||||
raw["services"][role] = service
|
||||
write_private(path, json.dumps(raw, indent=2) + "\n")
|
||||
for name in [
|
||||
"postgres_password",
|
||||
"s3_root_user",
|
||||
"s3_root_password",
|
||||
"grafana_password",
|
||||
]:
|
||||
write_private(SECRET / name, raw[name] + "\n", mode=0o644)
|
||||
for name in ["broker", "cache"]:
|
||||
admin = raw[name + "_admin"]
|
||||
lines = [
|
||||
"bind 127.0.0.1",
|
||||
"port 6379",
|
||||
"protected-mode yes",
|
||||
'save ""',
|
||||
"maxmemory 64mb" if name == "cache" else "maxmemory 192mb",
|
||||
"maxmemory-policy allkeys-lru"
|
||||
if name == "cache"
|
||||
else "maxmemory-policy noeviction",
|
||||
"user default off",
|
||||
"user admin on #"
|
||||
+ hashlib.sha256(admin.encode()).hexdigest()
|
||||
+ " ~* &* +@all",
|
||||
]
|
||||
if name == "cache":
|
||||
lines += [
|
||||
"user api on #"
|
||||
+ hashlib.sha256(raw["cache_api"].encode()).hexdigest()
|
||||
+ " ~user:* +get +set +ping +select +client|setinfo +client|setname"
|
||||
]
|
||||
else:
|
||||
lines += ["appendonly yes", "appendfsync always", "dir /data"]
|
||||
for role, commands in [
|
||||
("relay", "+xadd +waitaof"),
|
||||
(
|
||||
"worker",
|
||||
"+xgroup|create +xreadgroup +xautoclaim +xack +xdel",
|
||||
),
|
||||
]:
|
||||
lines += [
|
||||
"user "
|
||||
+ role
|
||||
+ " on #"
|
||||
+ hashlib.sha256(
|
||||
raw["services"][role]["broker_password"].encode()
|
||||
).hexdigest()
|
||||
+ " ~attachments +ping +select +client|setinfo +client|setname "
|
||||
+ commands
|
||||
]
|
||||
write_private(
|
||||
SECRET / (name + ".conf"), "\n".join(lines) + "\n", mode=0o644
|
||||
)
|
||||
write_private(SECRET / (name + "_admin"), admin + "\n", mode=0o644)
|
||||
|
||||
|
||||
def main():
|
||||
argparse.ArgumentParser(description=__doc__).parse_args()
|
||||
generate()
|
||||
print(
|
||||
"Local operator trust, scoped service credentials and bootstrap certificates prepared; existing secrets retained"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Явные операторские действия только над API текущего Compose-проекта."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def containers():
|
||||
ids = command("docker", "compose", "ps", "-q", "api").split()
|
||||
return json.loads(command("docker", "inspect", *ids)) if ids else []
|
||||
|
||||
|
||||
def alias(cid):
|
||||
code = (
|
||||
"import urllib.request; r=urllib.request.urlopen("
|
||||
"'http://127.0.0.1:8080/health/live',timeout=2); "
|
||||
"print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
return command("docker", "exec", cid, "python", "-c", code)
|
||||
|
||||
|
||||
def wait_count(count):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
data = containers()
|
||||
if len(data) == count and all(
|
||||
c["State"].get("Health", {}).get("Status") == "healthy"
|
||||
for c in data
|
||||
):
|
||||
# DNS и проверки HAProxy должны успеть увидеть новый адрес.
|
||||
time.sleep(3)
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError("Replica readiness")
|
||||
|
||||
|
||||
def main():
|
||||
action = sys.argv[1]
|
||||
data = containers()
|
||||
if action == "stop":
|
||||
target = os.environ["TARGET_INSTANCE_ID"]
|
||||
matches = [c for c in data if alias(c["Id"]) == target]
|
||||
if len(matches) != 1 or len(data) < 2:
|
||||
raise RuntimeError("Target must identify one running replica")
|
||||
command("docker", "stop", "--time", "10", matches[0]["Id"])
|
||||
print("Selected API stopped")
|
||||
elif action == "rolling":
|
||||
count = len(data)
|
||||
if count < 2:
|
||||
raise RuntimeError("Need at least two replicas")
|
||||
# Сначала добавляется готовая реплика, затем удаляется одна старая.
|
||||
for old in data:
|
||||
command(
|
||||
"docker",
|
||||
"compose",
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--no-recreate",
|
||||
"--scale",
|
||||
f"api={count + 1}",
|
||||
"api",
|
||||
)
|
||||
wait_count(count + 1)
|
||||
command("docker", "stop", "--time", "10", old["Id"])
|
||||
command("docker", "rm", old["Id"])
|
||||
wait_count(count)
|
||||
print("Sequential replacement completed")
|
||||
else:
|
||||
raise ValueError("Unknown action")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Read-only queries through an internal probe, without exposing admin ports."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from scripts.stand import compose
|
||||
|
||||
ENDPOINTS = {
|
||||
"prometheus": "http://prometheus:9090",
|
||||
"loki": "http://loki:3100",
|
||||
"tempo": "http://tempo:3200",
|
||||
"otel": "http://otel:13133",
|
||||
}
|
||||
|
||||
|
||||
def fetch(service, path, *, params=None, json_result=True):
|
||||
url = ENDPOINTS[service] + path
|
||||
if params:
|
||||
url += "?" + urlencode(params, doseq=True)
|
||||
code = (
|
||||
"import urllib.request; "
|
||||
f"r=urllib.request.urlopen(urllib.request.Request({url!r},headers={{'Accept':'application/json'}}),timeout=8); "
|
||||
"print(r.read().decode())"
|
||||
)
|
||||
text = compose("exec", "-T", "observer", "python", "-c", code)
|
||||
return json.loads(text) if json_result else text
|
||||
|
||||
|
||||
def query(expression, *, at=None):
|
||||
params = {"query": expression}
|
||||
if at is not None:
|
||||
params["time"] = str(at)
|
||||
result = fetch("prometheus", "/api/v1/query", params=params)
|
||||
assert result["status"] == "success"
|
||||
return result["data"]["result"]
|
||||
|
||||
|
||||
def scalar(expression):
|
||||
result = query(expression)
|
||||
return float(result[0]["value"][1]) if result else 0.0
|
||||
|
||||
|
||||
def queries(expressions):
|
||||
urls = {
|
||||
name: ENDPOINTS["prometheus"]
|
||||
+ "/api/v1/query?"
|
||||
+ urlencode({"query": expression})
|
||||
for name, expression in expressions.items()
|
||||
}
|
||||
code = (
|
||||
"import json,urllib.request\n"
|
||||
f"urls={urls!r}\n"
|
||||
"result={}\n"
|
||||
"for name,url in urls.items():\n"
|
||||
" with urllib.request.urlopen(url,timeout=8) as r: result[name]=json.load(r)['data']['result']\n"
|
||||
"print(json.dumps(result))"
|
||||
)
|
||||
return json.loads(compose("exec", "-T", "observer", "python", "-c", code))
|
||||
|
||||
|
||||
def logs(trace_id, *, start=None):
|
||||
return fetch(
|
||||
"loki",
|
||||
"/loki/api/v1/query_range",
|
||||
params={
|
||||
"query": '{service_name=~"messenger-api|messenger-worker|messenger-relay"} | trace_id="'
|
||||
+ trace_id
|
||||
+ '"',
|
||||
"start": str(int((start or time.time() - 3600) * 1e9)),
|
||||
"end": str(time.time_ns()),
|
||||
"limit": 500,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def normalize_id(value):
|
||||
if not value:
|
||||
return ""
|
||||
if len(value) in {16, 32} and all(c in "0123456789abcdef" for c in value):
|
||||
return value
|
||||
return base64.b64decode(value).hex()
|
||||
|
||||
|
||||
def spans(trace_id):
|
||||
result = fetch("tempo", "/api/traces/" + trace_id)
|
||||
flattened = []
|
||||
for batch in result.get("batches", result.get("resourceSpans", [])):
|
||||
resource = {
|
||||
a["key"]: next(iter(a["value"].values()))
|
||||
for a in batch.get("resource", {}).get("attributes", [])
|
||||
}
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for item in scope.get("spans", []):
|
||||
flattened.append(
|
||||
{
|
||||
"service": resource.get("service.name"),
|
||||
"version": resource.get("service.version"),
|
||||
"instance": resource.get("service.instance.id"),
|
||||
"name": item["name"],
|
||||
"kind": item.get("kind"),
|
||||
"trace_id": normalize_id(item.get("traceId")),
|
||||
"span_id": normalize_id(item.get("spanId")),
|
||||
"parent_span_id": normalize_id(
|
||||
item.get("parentSpanId")
|
||||
),
|
||||
"duration_seconds": (
|
||||
int(item["endTimeUnixNano"])
|
||||
- int(item["startTimeUnixNano"])
|
||||
)
|
||||
/ 1e9,
|
||||
"status": item.get("status", {}),
|
||||
"attributes": {
|
||||
a["key"]: next(iter(a["value"].values()))
|
||||
for a in item.get("attributes", [])
|
||||
},
|
||||
}
|
||||
)
|
||||
return flattened
|
||||
|
||||
|
||||
def wait(condition, *, timeout=90, interval=1):
|
||||
end = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
result = condition()
|
||||
if result:
|
||||
return result
|
||||
except (RuntimeError, ValueError, KeyError) as exc:
|
||||
last_error = type(exc).__name__
|
||||
time.sleep(interval)
|
||||
raise TimeoutError("Telemetry observation not reached: " + str(last_error))
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Operator-only, idempotent SQL roles and scoped S3 accounts."""
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.credentials import StaticProvider
|
||||
from minio.minioadmin import MinioAdmin
|
||||
from psycopg import sql
|
||||
|
||||
from scripts.bootstrap_security import OPERATOR, TRUST
|
||||
from scripts.stand import compose
|
||||
|
||||
|
||||
def postgres(raw):
|
||||
# The bootstrap SQL channel is the server's local Unix socket. No password
|
||||
# or SQL literal is placed in argv; stdin and output are never recorded.
|
||||
statements = [
|
||||
"REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON DATABASE messenger FROM PUBLIC;"
|
||||
]
|
||||
grants = {
|
||||
"api": {
|
||||
"SELECT": [
|
||||
"users",
|
||||
"sessions",
|
||||
"chats",
|
||||
"members",
|
||||
"messages",
|
||||
"idempotency",
|
||||
"attachments",
|
||||
"message_attachments",
|
||||
"upload_reservations",
|
||||
"jobs",
|
||||
"outbox",
|
||||
"attachment_variants",
|
||||
"effect_publications",
|
||||
],
|
||||
"INSERT": [
|
||||
"users",
|
||||
"sessions",
|
||||
"chats",
|
||||
"members",
|
||||
"messages",
|
||||
"idempotency",
|
||||
"attachments",
|
||||
"message_attachments",
|
||||
"upload_reservations",
|
||||
"jobs",
|
||||
"outbox",
|
||||
],
|
||||
"UPDATE": ["users", "idempotency", "jobs"],
|
||||
"DELETE": ["sessions", "upload_reservations"],
|
||||
},
|
||||
"worker": {
|
||||
"SELECT": [
|
||||
"jobs",
|
||||
"attachments",
|
||||
"attachment_variants",
|
||||
"effect_publications",
|
||||
"pipeline_faults",
|
||||
],
|
||||
"INSERT": [
|
||||
"attachment_variants",
|
||||
"effect_publications",
|
||||
"pipeline_events",
|
||||
"outbox",
|
||||
],
|
||||
"UPDATE": ["jobs", "attachments", "pipeline_faults"],
|
||||
},
|
||||
"relay": {
|
||||
"SELECT": ["jobs", "outbox", "attachments"],
|
||||
"INSERT": ["pipeline_events", "outbox"],
|
||||
"UPDATE": ["jobs", "attachments", "outbox"],
|
||||
},
|
||||
"observer": {
|
||||
"SELECT": [
|
||||
"jobs",
|
||||
"effect_publications",
|
||||
"pipeline_events",
|
||||
"job_slo_observations",
|
||||
],
|
||||
"INSERT": ["job_slo_observations"],
|
||||
"UPDATE": ["job_slo_observations"],
|
||||
},
|
||||
"reconciler": {
|
||||
"SELECT": [
|
||||
"jobs",
|
||||
"attachments",
|
||||
"attachment_variants",
|
||||
"upload_reservations",
|
||||
"message_attachments",
|
||||
"effect_publications",
|
||||
],
|
||||
"UPDATE": ["jobs", "attachments"],
|
||||
"DELETE": [
|
||||
"attachments",
|
||||
"attachment_variants",
|
||||
"upload_reservations",
|
||||
"jobs",
|
||||
"outbox",
|
||||
"job_slo_observations",
|
||||
],
|
||||
},
|
||||
}
|
||||
# SQL literals use psycopg's own adapter; names are fixed local roles.
|
||||
for role, permissions in grants.items():
|
||||
name = "svc_" + role
|
||||
password = raw["services"][role]["database_password"]
|
||||
statements.append(
|
||||
"DO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='"
|
||||
+ name
|
||||
+ "') THEN CREATE ROLE "
|
||||
+ name
|
||||
+ " LOGIN; END IF; END $$;"
|
||||
)
|
||||
statements.append(
|
||||
sql.SQL(
|
||||
"ALTER ROLE {} WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD {};"
|
||||
)
|
||||
.format(sql.Identifier(name), sql.Literal(password))
|
||||
.as_string()
|
||||
)
|
||||
statements.append(
|
||||
"GRANT CONNECT ON DATABASE messenger TO "
|
||||
+ name
|
||||
+ "; GRANT USAGE ON SCHEMA public TO "
|
||||
+ name
|
||||
+ ";"
|
||||
)
|
||||
statements.append(
|
||||
"REVOKE ALL ON ALL TABLES IN SCHEMA public FROM " + name + ";"
|
||||
)
|
||||
statements.append(
|
||||
"REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM " + name + ";"
|
||||
)
|
||||
for action, tables in permissions.items():
|
||||
statements.append(
|
||||
"GRANT "
|
||||
+ action
|
||||
+ " ON "
|
||||
+ ",".join(tables)
|
||||
+ " TO "
|
||||
+ name
|
||||
+ ";"
|
||||
)
|
||||
# Only append-only technical event/outbox IDs use sequences.
|
||||
sequences = {
|
||||
"api": ["outbox_id_seq"],
|
||||
"worker": ["outbox_id_seq", "pipeline_events_id_seq"],
|
||||
"relay": ["outbox_id_seq", "pipeline_events_id_seq"],
|
||||
}.get(role, [])
|
||||
if sequences:
|
||||
statements.append(
|
||||
"GRANT USAGE ON SEQUENCE "
|
||||
+ ",".join(sequences)
|
||||
+ " TO "
|
||||
+ name
|
||||
+ ";"
|
||||
)
|
||||
statements.append("GRANT EXECUTE ON FUNCTION login_wait(text) TO svc_api;")
|
||||
result = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-q",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
input="\n".join(statements),
|
||||
)
|
||||
assert "ERROR" not in result
|
||||
|
||||
|
||||
def s3(raw):
|
||||
context = ssl.create_default_context(cafile=TRUST / "ca.pem")
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
context.load_cert_chain(
|
||||
OPERATOR / "client/cert.pem", OPERATOR / "client/key.pem"
|
||||
)
|
||||
pool = urllib3.PoolManager(
|
||||
ssl_context=context,
|
||||
timeout=urllib3.Timeout(connect=2, read=10),
|
||||
retries=False,
|
||||
)
|
||||
credentials = StaticProvider(raw["s3_root_user"], raw["s3_root_password"])
|
||||
admin = MinioAdmin(
|
||||
"localhost:9007",
|
||||
credentials=credentials,
|
||||
secure=True,
|
||||
http_client=pool,
|
||||
)
|
||||
client = Minio(
|
||||
"localhost:9007",
|
||||
credentials=credentials,
|
||||
secure=True,
|
||||
http_client=pool,
|
||||
region="us-east-1",
|
||||
)
|
||||
for attempt in range(60):
|
||||
try:
|
||||
if not client.bucket_exists("messenger"):
|
||||
client.make_bucket("messenger")
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 59:
|
||||
raise RuntimeError("S3 TLS bootstrap unavailable") from None
|
||||
time.sleep(1)
|
||||
for role in ["api", "worker", "reconciler"]:
|
||||
statements = [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::messenger"],
|
||||
}
|
||||
]
|
||||
|
||||
def allow(actions, resource, condition=None, statements=statements):
|
||||
statement = {
|
||||
"Effect": "Allow",
|
||||
"Action": actions,
|
||||
"Resource": [resource],
|
||||
}
|
||||
if condition:
|
||||
statement["Condition"] = condition
|
||||
statements.append(statement)
|
||||
|
||||
allow(["s3:GetObject"], "arn:aws:s3:::messenger/objects/*")
|
||||
if role == "api":
|
||||
allow(["s3:PutObject"], "arn:aws:s3:::messenger/objects/staging/*")
|
||||
if role == "worker":
|
||||
allow(["s3:PutObject"], "arn:aws:s3:::messenger/objects/*/v*/*")
|
||||
if role == "reconciler":
|
||||
allow(["s3:DeleteObject"], "arn:aws:s3:::messenger/objects/*")
|
||||
allow(
|
||||
["s3:ListBucket"],
|
||||
"arn:aws:s3:::messenger",
|
||||
{"StringLike": {"s3:prefix": ["objects/*"]}},
|
||||
)
|
||||
values = raw["services"][role]["values"]
|
||||
admin.policy_add(
|
||||
"messenger-" + role,
|
||||
policy={"Version": "2012-10-17", "Statement": statements},
|
||||
)
|
||||
admin.user_add(values["S3_ACCESS_KEY"], values["S3_SECRET_KEY"])
|
||||
admin.attach_policy(
|
||||
["messenger-" + role], user=values["S3_ACCESS_KEY"]
|
||||
)
|
||||
pool.clear()
|
||||
|
||||
|
||||
def main():
|
||||
raw = json.loads((OPERATOR / "service-secrets.json").read_text())
|
||||
postgres(raw)
|
||||
s3(raw)
|
||||
print("SQL role grants and scoped S3 accounts prepared; no values printed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,633 @@
|
||||
"""Thirty-minute controlled SLO study with real DB/worker/backend failures."""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
os.environ.setdefault("COMPOSE_FILE", "compose.yaml:compose.test.yaml")
|
||||
from scripts.observe import fetch, logs, queries, spans, wait
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
||||
|
||||
ERRORS = 'haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}'
|
||||
RESPONSES = 'haproxy_backend_http_responses_total{proxy="messenger"}'
|
||||
SIGNALS = {
|
||||
"api_error_ratio_1m": f"sum(rate({ERRORS}[1m])) / clamp_min(sum(rate({RESPONSES}[1m])),0.001)",
|
||||
"queue_depth": "max(messenger_queue_depth)",
|
||||
"oldest_job_age": "max(messenger_oldest_job_age_seconds)",
|
||||
"worker_busy": "sum(messenger_worker_busy)",
|
||||
"worker_attempts": "sum(messenger_job_attempts_total)",
|
||||
"pool_used": 'sum(messenger_db_pool_used{service_name="messenger-api"})',
|
||||
"pool_waiting": 'sum(messenger_db_pool_waiting{service_name="messenger-api"})',
|
||||
"http_p95": "histogram_quantile(0.95,sum by(le)(rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||
"slo_good": 'sum(messenger_slo_decisions_total{outcome="good"})',
|
||||
"slo_bad": 'sum(messenger_slo_decisions_total{outcome="bad"})',
|
||||
"collector_received_spans": "sum(otelcol_receiver_accepted_spans)",
|
||||
"collector_sent_spans": "sum(otelcol_exporter_sent_spans)",
|
||||
"collector_received_logs": "sum(otelcol_receiver_accepted_log_records)",
|
||||
"collector_sent_logs": "sum(otelcol_exporter_sent_log_records)",
|
||||
"collector_failed_spans": "sum(otelcol_exporter_send_failed_spans)",
|
||||
"collector_queue": "sum(otelcol_exporter_queue_size)",
|
||||
"collector_queue_capacity": "sum(otelcol_exporter_queue_capacity)",
|
||||
"collector_memory": 'otelcol_process_memory_rss{job="collector"}',
|
||||
"app_memory": "sum(messenger_process_memory_bytes)",
|
||||
}
|
||||
BURN_ALERTS = {"ApiFastBurn", "ApiSlowBurn", "ReadyFastBurn", "ReadySlowBurn"}
|
||||
|
||||
|
||||
def snapshot(phase):
|
||||
observed = queries(SIGNALS)
|
||||
values = {}
|
||||
for key, rows in observed.items():
|
||||
value = float(rows[0]["value"][1]) if rows else None
|
||||
values[key] = (
|
||||
value if value is not None and math.isfinite(value) else None
|
||||
)
|
||||
alerts = fetch("prometheus", "/api/v1/alerts")["data"]["alerts"]
|
||||
return {
|
||||
"at": time.time(),
|
||||
"phase": phase,
|
||||
"signals": values,
|
||||
"alerts": [
|
||||
{
|
||||
"name": a["labels"]["alertname"],
|
||||
"state": a["state"],
|
||||
"active_at": a.get("activeAt"),
|
||||
}
|
||||
for a in alerts
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def firing(samples):
|
||||
return {
|
||||
a["name"]
|
||||
for sample in samples
|
||||
for a in sample["alerts"]
|
||||
if a["state"] == "firing"
|
||||
}
|
||||
|
||||
|
||||
class Workload:
|
||||
def __init__(self, client, headers, chat):
|
||||
self.client, self.headers, self.chat = client, headers, chat
|
||||
self.stop = threading.Event()
|
||||
self.phase = "warmup"
|
||||
self.requests = []
|
||||
self.uploads = []
|
||||
self.lock = threading.Lock()
|
||||
self.slots = threading.BoundedSemaphore(16)
|
||||
self.pool = ThreadPoolExecutor(max_workers=16)
|
||||
image = io.BytesIO()
|
||||
Image.new("RGB", (320, 200), (39, 102, 157)).save(image, "PNG")
|
||||
self.raw = image.getvalue()
|
||||
self.threads = [
|
||||
threading.Thread(target=self.schedule_messages),
|
||||
threading.Thread(target=self.schedule_uploads),
|
||||
]
|
||||
|
||||
def write(self):
|
||||
started, phase, trace_id = time.time(), self.phase, uuid4().hex
|
||||
status, identity = 0, ""
|
||||
try:
|
||||
response = self.client.post(
|
||||
f"/api/v1/chats/{self.chat}/messages",
|
||||
headers={
|
||||
**self.headers,
|
||||
"Idempotency-Key": uuid4().hex,
|
||||
"traceparent": "00-"
|
||||
+ trace_id
|
||||
+ "-"
|
||||
+ uuid4().hex[:16]
|
||||
+ "-01",
|
||||
},
|
||||
json={"text": "Synthetic SLO message " + uuid4().hex},
|
||||
)
|
||||
status = response.status_code
|
||||
if status == 201:
|
||||
identity = response.json()["id"]
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
finally:
|
||||
with self.lock:
|
||||
self.requests.append(
|
||||
[
|
||||
started,
|
||||
phase,
|
||||
status,
|
||||
time.time() - started,
|
||||
trace_id,
|
||||
identity,
|
||||
]
|
||||
)
|
||||
self.slots.release()
|
||||
|
||||
def schedule_messages(self):
|
||||
next_at = time.monotonic()
|
||||
while not self.stop.is_set():
|
||||
if self.slots.acquire(blocking=False):
|
||||
self.pool.submit(self.write)
|
||||
else:
|
||||
with self.lock:
|
||||
self.requests.append(
|
||||
[time.time(), self.phase, -1, 0, "", ""]
|
||||
)
|
||||
next_at += 0.25
|
||||
self.stop.wait(max(0, next_at - time.monotonic()))
|
||||
|
||||
def schedule_uploads(self):
|
||||
while not self.stop.is_set():
|
||||
started, phase, trace_id = time.time(), self.phase, uuid4().hex
|
||||
status, identity = 0, ""
|
||||
try:
|
||||
response = self.client.post(
|
||||
f"/api/v1/chats/{self.chat}/attachments",
|
||||
params={"filename": "synthetic-slo.png"},
|
||||
content=self.raw,
|
||||
headers={
|
||||
**self.headers,
|
||||
"Content-Type": "image/png",
|
||||
"traceparent": "00-"
|
||||
+ trace_id
|
||||
+ "-"
|
||||
+ uuid4().hex[:16]
|
||||
+ "-01",
|
||||
},
|
||||
)
|
||||
status = response.status_code
|
||||
if status == 202:
|
||||
identity = response.json()["id"]
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
with self.lock:
|
||||
self.uploads.append(
|
||||
[started, phase, status, identity, trace_id]
|
||||
)
|
||||
self.stop.wait(max(0, 5 - (time.time() - started)))
|
||||
|
||||
def start(self):
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
for thread in self.threads:
|
||||
thread.join(20)
|
||||
self.pool.shutdown(wait=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/slo-research-first.json")
|
||||
parser.add_argument("--minimum-seconds", type=int, default=1800)
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists(), "Choose a new output path"
|
||||
report = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"scope": "full30m"
|
||||
if args.minimum_seconds >= 1800
|
||||
else "short-development",
|
||||
"profile": {
|
||||
"messages_per_second": 4,
|
||||
"max_inflight": 16,
|
||||
"upload_every_seconds": 5,
|
||||
"image_pixels": [320, 200],
|
||||
},
|
||||
"complete": False,
|
||||
"samples": [],
|
||||
"phases": [],
|
||||
}
|
||||
study_started = time.monotonic()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
load = None
|
||||
trigger = "lab6_slo_delay_" + uuid4().hex[:8]
|
||||
with httpx.Client(
|
||||
base_url=BASE,
|
||||
timeout=8,
|
||||
trust_env=False,
|
||||
limits=httpx.Limits(max_connections=24, max_keepalive_connections=24),
|
||||
) as client:
|
||||
ready(timeout=90)
|
||||
config = json.loads(compose("config", "--format", "json"))
|
||||
report["container_limits"] = {
|
||||
name: {
|
||||
k: int(service[k])
|
||||
if k in {"mem_limit", "memswap_limit", "scale"}
|
||||
else service[k]
|
||||
for k in ["cpus", "mem_limit", "memswap_limit", "scale"]
|
||||
if k in service
|
||||
}
|
||||
for name, service in config["services"].items()
|
||||
}
|
||||
report["docker_vm"] = json.loads(
|
||||
command(
|
||||
[
|
||||
"docker",
|
||||
"info",
|
||||
"--format",
|
||||
'{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}',
|
||||
]
|
||||
)
|
||||
)
|
||||
report["runtime_versions"] = sorted(
|
||||
{
|
||||
row["metric"].get("service_version", "unknown")
|
||||
for row in queries(
|
||||
{"versions": "messenger_process_memory_bytes"}
|
||||
)["versions"]
|
||||
}
|
||||
)
|
||||
user, _, session = actor(client)
|
||||
headers = auth(session)
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers,
|
||||
json={
|
||||
"title": "Synthetic SLO experiment",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
chat = response.json()["id"]
|
||||
load = Workload(client, headers, chat)
|
||||
workload = load
|
||||
|
||||
def save():
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
|
||||
def hold(name, seconds, *, until_clear=None, max_seconds=None):
|
||||
load.phase = name
|
||||
phase = {
|
||||
"name": name,
|
||||
"start": time.time(),
|
||||
"planned_seconds": seconds,
|
||||
"maximum_seconds": max_seconds or seconds,
|
||||
}
|
||||
report["phases"].append(phase)
|
||||
minimum_end = time.monotonic() + seconds
|
||||
deadline = time.monotonic() + (max_seconds or seconds)
|
||||
start_index = len(report["samples"])
|
||||
while time.monotonic() < deadline:
|
||||
sample = snapshot(name)
|
||||
report["samples"].append(sample)
|
||||
save()
|
||||
if (
|
||||
until_clear is not None
|
||||
and time.monotonic() >= minimum_end
|
||||
and not until_clear.intersection(firing([sample]))
|
||||
):
|
||||
break
|
||||
time.sleep(min(5, max(0, deadline - time.monotonic())))
|
||||
phase["end"] = time.time()
|
||||
phase["firing"] = sorted(firing(report["samples"][start_index:]))
|
||||
return phase
|
||||
|
||||
def db_delay(on):
|
||||
if on:
|
||||
sql(
|
||||
f"CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.chat_id='{chat}'::uuid THEN PERFORM pg_sleep(3); END IF; RETURN NEW; END $$; CREATE TRIGGER {trigger} BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION {trigger}()"
|
||||
)
|
||||
else:
|
||||
sql(
|
||||
f"DROP TRIGGER IF EXISTS {trigger} ON messages; DROP FUNCTION IF EXISTS {trigger}()"
|
||||
)
|
||||
|
||||
try:
|
||||
load.start()
|
||||
warm = hold("warmup", 300)
|
||||
settled = [
|
||||
s for s in report["samples"] if s["at"] >= warm["end"] - 60
|
||||
]
|
||||
assert not BURN_ALERTS.intersection(firing(settled)), (
|
||||
"Baseline is not clean"
|
||||
)
|
||||
assert (
|
||||
report["samples"][-1]["signals"]["collector_memory"]
|
||||
is not None
|
||||
)
|
||||
report["baseline"] = snapshot("baseline")
|
||||
for signal in ["api", "ready"]:
|
||||
if signal == "api":
|
||||
activate, restore = (
|
||||
lambda: db_delay(True),
|
||||
lambda: db_delay(False),
|
||||
)
|
||||
else:
|
||||
|
||||
def activate():
|
||||
return compose("stop", "--timeout", "1", "worker")
|
||||
|
||||
def restore():
|
||||
return compose(
|
||||
"up", "-d", "--no-deps", "--no-recreate", "worker"
|
||||
)
|
||||
|
||||
brief_started = time.time()
|
||||
activate()
|
||||
brief = hold(signal + "_brief", 5)
|
||||
restore()
|
||||
settle = hold(
|
||||
signal + "_brief_recovery", 120 if signal == "api" else 60
|
||||
)
|
||||
assert not BURN_ALERTS.intersection(
|
||||
brief["firing"] + settle["firing"]
|
||||
), "Brief incident triggered paging"
|
||||
report.setdefault("short_spikes", []).append(
|
||||
{
|
||||
"signal": signal,
|
||||
"action_started": brief_started,
|
||||
"paging_events": 0,
|
||||
}
|
||||
)
|
||||
action_started = time.time()
|
||||
activate()
|
||||
action_finished = time.time()
|
||||
degraded = hold(
|
||||
signal + "_sustained", 180 if signal == "api" else 150
|
||||
)
|
||||
restore_started = time.time()
|
||||
restore()
|
||||
restore_finished = time.time()
|
||||
expected = (
|
||||
{"ApiFastBurn", "ApiSlowBurn", "ApiHighErrorRate"}
|
||||
if signal == "api"
|
||||
else {"ReadyFastBurn", "ReadySlowBurn", "QueueLagGrowing"}
|
||||
)
|
||||
recovered = hold(
|
||||
signal + "_recovery",
|
||||
150 if signal == "api" else 240,
|
||||
until_clear=expected,
|
||||
max_seconds=600,
|
||||
)
|
||||
assert expected <= set(degraded["firing"]), (
|
||||
signal,
|
||||
degraded["firing"],
|
||||
)
|
||||
last = report["samples"][-1]
|
||||
assert not expected.intersection(firing([last])), (
|
||||
"Incident alerts did not resolve"
|
||||
)
|
||||
points = [
|
||||
s
|
||||
for s in report["samples"]
|
||||
if action_finished <= s["at"] <= recovered["end"]
|
||||
]
|
||||
timings = {}
|
||||
for name in sorted(expected):
|
||||
first = next(
|
||||
s["at"] for s in points if name in firing([s])
|
||||
)
|
||||
resolved = next(
|
||||
s["at"]
|
||||
for s in points
|
||||
if s["at"] >= restore_finished
|
||||
and name not in firing([s])
|
||||
)
|
||||
timings[name] = {
|
||||
"detect_seconds": round(first - action_finished, 3),
|
||||
"resolve_seconds": round(
|
||||
resolved - restore_finished, 3
|
||||
),
|
||||
}
|
||||
report.setdefault("incidents", []).append(
|
||||
{
|
||||
"signal": signal,
|
||||
"action_started": action_started,
|
||||
"action_finished": action_finished,
|
||||
"restore_started": restore_started,
|
||||
"restore_finished": restore_finished,
|
||||
"timings": timings,
|
||||
}
|
||||
)
|
||||
if signal == "api":
|
||||
candidates = [
|
||||
r
|
||||
for r in load.requests
|
||||
if action_finished <= r[0] <= restore_started
|
||||
and r[2] >= 500
|
||||
]
|
||||
assert candidates
|
||||
items = wait(
|
||||
lambda identity=candidates[0][4]: spans(identity)
|
||||
)
|
||||
assert any(
|
||||
s["name"] == "db.postgresql"
|
||||
and s["duration_seconds"] >= 2
|
||||
and s["status"].get("code") in {2, "STATUS_CODE_ERROR"}
|
||||
for s in items
|
||||
)
|
||||
report["database_diagnostic_trace"] = items
|
||||
else:
|
||||
assert (
|
||||
max(
|
||||
s["signals"]["oldest_job_age"] or 0 for s in points
|
||||
)
|
||||
> 20
|
||||
)
|
||||
assert (
|
||||
max(s["signals"]["queue_depth"] or 0 for s in points)
|
||||
> 0
|
||||
)
|
||||
accepted = [
|
||||
r
|
||||
for r in load.uploads
|
||||
if action_finished <= r[0] <= restore_started
|
||||
and r[2] == 202
|
||||
]
|
||||
assert accepted
|
||||
report["worker_recovered_trace"] = wait(
|
||||
lambda identity=accepted[0][4]: spans(identity)
|
||||
)
|
||||
report["worker_recovered_attachment"] = accepted[0][3]
|
||||
outage_before = snapshot("backend_before")
|
||||
outage_started = time.time()
|
||||
compose("stop", "--timeout", "1", "loki", "tempo")
|
||||
outage = hold("backend_unavailable", 90)
|
||||
points = [
|
||||
s
|
||||
for s in report["samples"]
|
||||
if s["phase"] == "backend_unavailable"
|
||||
]
|
||||
assert max(
|
||||
s["signals"]["collector_failed_spans"] or 0 for s in points
|
||||
) > (outage_before["signals"]["collector_failed_spans"] or 0)
|
||||
assert all(
|
||||
s["signals"]["collector_queue"] is not None
|
||||
and s["signals"]["collector_queue_capacity"] is not None
|
||||
and s["signals"]["collector_memory"] is not None
|
||||
for s in points
|
||||
)
|
||||
assert all(
|
||||
(s["signals"]["collector_queue"] or 0)
|
||||
<= (s["signals"]["collector_queue_capacity"] or 0)
|
||||
for s in points
|
||||
)
|
||||
assert (
|
||||
max(s["signals"]["collector_memory"] for s in points)
|
||||
< report["container_limits"]["otel"]["mem_limit"]
|
||||
)
|
||||
assert not BURN_ALERTS.intersection(outage["firing"])
|
||||
during = [
|
||||
r for r in load.requests if r[1] == "backend_unavailable"
|
||||
]
|
||||
assert during and all(r[2] == 201 for r in during)
|
||||
before_ready = sql(
|
||||
"SELECT count(*) FROM attachments WHERE state='ready'"
|
||||
)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "loki", "tempo")
|
||||
wait(lambda: fetch("loki", "/ready", json_result=False))
|
||||
wait(lambda: fetch("tempo", "/ready", json_result=False))
|
||||
hold("backend_recovery", 60)
|
||||
restored = next(
|
||||
r
|
||||
for r in reversed(load.uploads)
|
||||
if r[1] == "backend_recovery" and r[2] == 202
|
||||
)
|
||||
wait(
|
||||
lambda: any(
|
||||
s["name"] == "attachment.process"
|
||||
for s in spans(restored[4])
|
||||
)
|
||||
)
|
||||
wait(lambda: logs(restored[4]).get("data", {}).get("result"))
|
||||
report["backend_outage"] = {
|
||||
"started": outage_started,
|
||||
"finished": outage["end"],
|
||||
"before": outage_before,
|
||||
"after": snapshot("backend_after"),
|
||||
"ready_count_before_backend_recovery": int(before_ready),
|
||||
"successful_writes_during_outage": len(during),
|
||||
"restored_trace_id": restored[4],
|
||||
"queue_bounded": True,
|
||||
"collector_rss_below_limit": True,
|
||||
"send_failure_counter_counts_attempts_not_unique_loss": True,
|
||||
}
|
||||
remaining = args.minimum_seconds - (
|
||||
time.monotonic() - study_started
|
||||
)
|
||||
if remaining > 0:
|
||||
hold("steady_after_recovery", remaining)
|
||||
load.close()
|
||||
load = None
|
||||
# Read through the public API: a successful SQL insert alone is not
|
||||
# proof that every acknowledged message remains accessible.
|
||||
seen, cursor = set(), None
|
||||
while True:
|
||||
page = client.get(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers=headers,
|
||||
params={
|
||||
"limit": 100,
|
||||
**({"cursor": cursor} if cursor else {}),
|
||||
},
|
||||
)
|
||||
page.raise_for_status()
|
||||
data = page.json()
|
||||
ids = [row["id"] for row in data["items"]]
|
||||
assert len(ids) == len(set(ids)) and not seen.intersection(ids)
|
||||
seen.update(ids)
|
||||
cursor = data.get("next_cursor")
|
||||
if not cursor:
|
||||
break
|
||||
expected_messages = {
|
||||
r[5] for r in workload.requests if r[2] == 201
|
||||
}
|
||||
assert seen == expected_messages
|
||||
accepted_uploads = [r for r in workload.uploads if r[2] == 202]
|
||||
for row in accepted_uploads:
|
||||
|
||||
def completed(identity=row[3]):
|
||||
response = client.get(
|
||||
f"/api/v1/attachments/{identity}", headers=headers
|
||||
)
|
||||
return (
|
||||
response.status_code == 200
|
||||
and response.json()["status"] == "ready"
|
||||
)
|
||||
|
||||
wait(completed, timeout=120)
|
||||
for row in accepted_uploads[
|
||||
:: max(1, len(accepted_uploads) // 10)
|
||||
]:
|
||||
response = client.get(
|
||||
f"/api/v1/attachments/{row[3]}/content", headers=headers
|
||||
)
|
||||
assert (
|
||||
response.status_code == 200
|
||||
and response.content == workload.raw
|
||||
)
|
||||
report["preservation"] = {
|
||||
"acknowledged_messages": len(expected_messages),
|
||||
"accessible_messages": len(seen),
|
||||
"accepted_uploads": len(accepted_uploads),
|
||||
"all_accepted_uploads_ready": True,
|
||||
"sampled_originals_match": True,
|
||||
}
|
||||
report["rules"] = fetch("prometheus", "/api/v1/rules")
|
||||
report["final_30m_sli"] = queries(
|
||||
{
|
||||
"api_good_ratio": f"1 - sum(increase({ERRORS}[30m])) / clamp_min(sum(increase({RESPONSES}[30m])),1)",
|
||||
"ready_good_ratio": 'sum(increase(messenger_slo_decisions_total{outcome="good"}[30m])) / clamp_min(sum(increase(messenger_slo_decisions_total[30m])),1)',
|
||||
}
|
||||
)
|
||||
report["complete"] = True
|
||||
finally:
|
||||
try:
|
||||
db_delay(False)
|
||||
finally:
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--no-recreate",
|
||||
"worker",
|
||||
"loki",
|
||||
"tempo",
|
||||
)
|
||||
if load is not None:
|
||||
load.close()
|
||||
report["elapsed_seconds"] = round(
|
||||
time.monotonic() - study_started, 3
|
||||
)
|
||||
request_path = output.with_name(output.stem + "-requests.csv")
|
||||
with request_path.open("w") as stream:
|
||||
writer = csv.writer(stream)
|
||||
writer.writerow(
|
||||
[
|
||||
"timestamp",
|
||||
"phase",
|
||||
"status",
|
||||
"seconds",
|
||||
"trace_id",
|
||||
"message_id",
|
||||
]
|
||||
)
|
||||
writer.writerows(workload.requests)
|
||||
report["requests_csv"] = request_path.name
|
||||
report["request_statuses"] = dict(
|
||||
Counter(str(r[2]) for r in workload.requests)
|
||||
)
|
||||
report["uploads"] = workload.uploads
|
||||
save()
|
||||
print(
|
||||
"PASS: short/sustained SLO incidents, detection/resolution and controlled false paging"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
docker compose restart api postgres cache s3 broker relay worker lb
|
||||
docker compose up -d --no-build --no-recreate --wait
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec python3 scripts/cluster.py rolling
|
||||
@@ -0,0 +1,142 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = os.environ.get("BASE_URL", "https://localhost:8443")
|
||||
|
||||
|
||||
def command(args, *, input=None):
|
||||
result = subprocess.run(
|
||||
args, cwd=ROOT, input=input, capture_output=True, text=True
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"Command failed: "
|
||||
+ args[0]
|
||||
+ "; "
|
||||
+ result.stderr.replace(str(ROOT), "<repository>")
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return command(["docker", "compose", *args], input=input)
|
||||
|
||||
|
||||
def sql(query, *, database="messenger"):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
database,
|
||||
"-A",
|
||||
"-t",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-c",
|
||||
query,
|
||||
)
|
||||
|
||||
|
||||
def cache(command_name, *args):
|
||||
script = (
|
||||
'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; '
|
||||
'exec valkey-cli "$@"'
|
||||
)
|
||||
return compose(
|
||||
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
|
||||
)
|
||||
|
||||
|
||||
def ready(base=BASE, *, timeout=30):
|
||||
end = time.monotonic() + timeout
|
||||
import ssl
|
||||
|
||||
context = ssl.create_default_context(cafile=ROOT / "trust/ca.pem")
|
||||
with httpx.Client(
|
||||
base_url=base, trust_env=False, timeout=6, verify=context
|
||||
) as client:
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
if client.get("/health/ready").status_code == 200:
|
||||
return
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise TimeoutError("API readiness")
|
||||
|
||||
|
||||
def actor(client):
|
||||
username = "verify_" + uuid4().hex[:20]
|
||||
password = "Synthetic-" + uuid4().hex + ":🌍"
|
||||
result = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Synthetic",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert result.status_code == 201
|
||||
user = result.json()
|
||||
session = client.post(
|
||||
"/api/v1/auth/sessions", auth=httpx.BasicAuth(username, password)
|
||||
)
|
||||
assert session.status_code == 201
|
||||
return user, password, session.json()
|
||||
|
||||
|
||||
def auth(session):
|
||||
return {"Authorization": "Bearer " + session["token"]}
|
||||
|
||||
|
||||
def extra_api(*, ttl=3600, pool_size=1):
|
||||
name = "mtusi-lab6-test-" + uuid4().hex[:10]
|
||||
compose(
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"-e",
|
||||
"SESSION_TTL_SECONDS=" + str(ttl),
|
||||
"-e",
|
||||
"DB_POOL_SIZE=" + str(pool_size),
|
||||
"-p",
|
||||
"127.0.0.1::8080",
|
||||
"api",
|
||||
)
|
||||
try:
|
||||
info = json.loads(command(["docker", "inspect", name]))[0]
|
||||
base = (
|
||||
"http://127.0.0.1:"
|
||||
+ info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
|
||||
)
|
||||
ready(base)
|
||||
return name, base
|
||||
except Exception:
|
||||
command(["docker", "rm", "-f", name])
|
||||
raise
|
||||
|
||||
|
||||
def instances():
|
||||
data = {}
|
||||
for role in ["api", "postgres", "cache"]:
|
||||
cid = compose("ps", "-q", role)
|
||||
info = json.loads(command(["docker", "inspect", cid]))[0]
|
||||
data[role] = {
|
||||
"container": cid[:12],
|
||||
"pid": info["State"]["Pid"],
|
||||
"started_at": info["State"]["StartedAt"],
|
||||
}
|
||||
return data
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec python3 scripts/cluster.py stop
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
docker compose stop --timeout 1 worker
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Explicit local operator bootstrap; an ordinary API restart needs no unseal."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from scripts.bao_operator import Operator
|
||||
from scripts.bootstrap_security import OPERATOR, generate
|
||||
from scripts.prepare_dependencies import main as dependencies
|
||||
from scripts.prepare_dependencies import postgres
|
||||
from scripts.stand import ROOT, command, compose, ready
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--build", action="store_true")
|
||||
args = parser.parse_args()
|
||||
generate()
|
||||
os.environ.setdefault("VCS_REF", command(["git", "rev-parse", "HEAD"]))
|
||||
if args.build:
|
||||
subprocess.run(
|
||||
["docker", "compose", "build", "api", "s3"], cwd=ROOT, check=True
|
||||
)
|
||||
compose("run", "--rm", "--no-deps", "identity-init")
|
||||
compose(
|
||||
"up", "-d", "--no-deps", "openbao", "postgres", "cache", "broker", "s3"
|
||||
)
|
||||
operator = Operator()
|
||||
try:
|
||||
for attempt in range(90):
|
||||
try:
|
||||
operator.call("GET", "sys/init")
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 89:
|
||||
raise RuntimeError(
|
||||
"OpenBao TLS startup unavailable"
|
||||
) from None
|
||||
time.sleep(1)
|
||||
operator.init()
|
||||
operator.unseal()
|
||||
operator.configure()
|
||||
finally:
|
||||
operator.close()
|
||||
agents = [
|
||||
"identity-" + r
|
||||
for r in [
|
||||
"openbao",
|
||||
"api",
|
||||
"worker",
|
||||
"relay",
|
||||
"observer",
|
||||
"reconciler",
|
||||
"postgres",
|
||||
"cache",
|
||||
"broker",
|
||||
"s3",
|
||||
"otel",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
]
|
||||
]
|
||||
compose("up", "-d", "--no-deps", *agents)
|
||||
compose("up", "-d", "--no-deps", "postgres-tls")
|
||||
compose(
|
||||
"--profile", "maintenance", "up", "-d", "--no-deps", "identity-migrate"
|
||||
)
|
||||
try:
|
||||
compose(
|
||||
"--profile", "maintenance", "run", "--rm", "--no-deps", "migrate"
|
||||
)
|
||||
finally:
|
||||
compose("--profile", "maintenance", "stop", "identity-migrate")
|
||||
postgres(json.loads((OPERATOR / "service-secrets.json").read_text()))
|
||||
compose("up", "-d", "--no-deps", "telemetry-init")
|
||||
compose("wait", "telemetry-init")
|
||||
backends = ["otel", "prometheus", "loki", "tempo", "grafana", "lb"]
|
||||
compose("up", "-d", "--no-deps", *backends)
|
||||
gates = [
|
||||
r + "-tls"
|
||||
for r in [
|
||||
"postgres",
|
||||
"s3",
|
||||
"cache",
|
||||
"broker",
|
||||
"otel",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
"lb",
|
||||
]
|
||||
]
|
||||
compose("up", "-d", "--no-deps", *gates, "identity-lb")
|
||||
dependencies()
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"api",
|
||||
"relay",
|
||||
"worker",
|
||||
"observer",
|
||||
"reconciler",
|
||||
)
|
||||
ready(timeout=120)
|
||||
print("Secure stand ready at https://localhost:8443; values remain local")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,286 @@
|
||||
import argparse
|
||||
import atexit
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROGRESS = {}
|
||||
|
||||
|
||||
def save_incomplete():
|
||||
receipt = PROGRESS.get("receipt")
|
||||
if receipt and receipt.get("result") != "PASS":
|
||||
target = PROGRESS["output"].with_name(
|
||||
PROGRESS["output"].stem + "-failed.json"
|
||||
)
|
||||
if target.exists():
|
||||
target = target.with_name(
|
||||
target.stem + "-" + uuid4().hex[:8] + target.suffix
|
||||
)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(
|
||||
json.dumps(
|
||||
{**receipt, "result": "INCOMPLETE"},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
|
||||
atexit.register(save_incomplete)
|
||||
|
||||
|
||||
def run(args, *, cwd, env, expected=0):
|
||||
result = subprocess.run(
|
||||
args, cwd=cwd, env=env, capture_output=True, text=True
|
||||
)
|
||||
|
||||
def redact(text):
|
||||
return (
|
||||
text.replace(str(cwd), "<clean-clone>")
|
||||
.replace(str(ROOT), "<repository>")
|
||||
.replace(str(Path.home()), "<home>")
|
||||
)
|
||||
|
||||
if result.returncode != expected:
|
||||
if "receipt" in PROGRESS:
|
||||
PROGRESS["receipt"]["failed_action"] = redact(" ".join(args))
|
||||
raise RuntimeError(redact(result.stdout + result.stderr))
|
||||
return redact(result.stdout.strip())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/clean-clone.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
if output.exists():
|
||||
raise SystemExit("Choose new output path")
|
||||
assert not subprocess.check_output(
|
||||
["git", "status", "--porcelain"], cwd=ROOT
|
||||
)
|
||||
sha = subprocess.check_output(
|
||||
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
|
||||
).strip()
|
||||
identity = uuid4().hex[:10]
|
||||
project = "mtusi-lab6-clean-" + identity
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(("127.0.0.1", 0))
|
||||
public_port = str(reservation.getsockname()[1])
|
||||
with socket.socket() as grafana_reservation:
|
||||
grafana_reservation.bind(("127.0.0.1", 0))
|
||||
grafana_port = str(grafana_reservation.getsockname()[1])
|
||||
env = {
|
||||
**os.environ,
|
||||
"COMPOSE_PROJECT_NAME": project,
|
||||
"API_IMAGE": "mtusi-messenger:lab6-clean-" + identity,
|
||||
"PUBLIC_PORT": public_port,
|
||||
"GRAFANA_PORT": grafana_port,
|
||||
"VCS_REF": sha,
|
||||
"COMPOSE_FILE": "compose.yaml:compose.test.yaml",
|
||||
"NO_PROXY": "localhost,127.0.0.1",
|
||||
"no_proxy": "localhost,127.0.0.1",
|
||||
}
|
||||
receipt = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"source_commit": sha,
|
||||
"fresh_secrets_environment_and_volumes": True,
|
||||
"command": "python scripts/verify_clean.py",
|
||||
"fixed_host_port_for_restart": int(public_port),
|
||||
}
|
||||
PROGRESS.update(receipt=receipt, output=output)
|
||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab6-clean-") as temporary:
|
||||
clone = Path(temporary) / "lab6"
|
||||
run(
|
||||
[
|
||||
"git",
|
||||
"clone",
|
||||
"--no-hardlinks",
|
||||
"--branch",
|
||||
"solution/bvt2301-maslov",
|
||||
str(ROOT),
|
||||
str(clone),
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
)
|
||||
for name in [".env", ".venv", "secrets"]:
|
||||
assert not (clone / name).exists()
|
||||
run(["uv", "sync", "--locked"], cwd=clone, env=env)
|
||||
receipt["static_checks"] = run(
|
||||
["make", "check", "validate", "lint", "PYTHON=.venv/bin/python"],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
receipt["unit_tests"] = run(["make", "unit"], cwd=clone, env=env)
|
||||
run(["make", "bootstrap"], cwd=clone, env=env)
|
||||
try:
|
||||
run(
|
||||
["docker", "compose", "up", "-d", "--build", "--wait"],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
env["BASE_URL"] = "http://127.0.0.1:" + public_port
|
||||
receipt["smoke"] = run(
|
||||
["make", "test", "BASE_URL=" + env["BASE_URL"]],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
receipt["http_tests"] = run(
|
||||
[".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env
|
||||
)
|
||||
for module, extra in [
|
||||
("verify_telemetry", []),
|
||||
(
|
||||
"verify_observability_persistence",
|
||||
["--causal-evidence", "evidence/clean-telemetry.json"],
|
||||
),
|
||||
]:
|
||||
name = (
|
||||
"telemetry"
|
||||
if module == "verify_telemetry"
|
||||
else "observability-persistence"
|
||||
)
|
||||
run(
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts." + module,
|
||||
"--output",
|
||||
"evidence/clean-" + name + ".json",
|
||||
*extra,
|
||||
],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
receipt[name] = json.loads(
|
||||
(clone / ("evidence/clean-" + name + ".json")).read_text()
|
||||
)
|
||||
run(
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts.verify_cluster",
|
||||
"--output",
|
||||
"evidence/clean-cluster.json",
|
||||
],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
for command_args in [
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts.verify_cleanup",
|
||||
"seed",
|
||||
"--seed",
|
||||
"evidence/clean-gc-seed.json",
|
||||
],
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts.verify_pipeline",
|
||||
"--output",
|
||||
"evidence/clean-pipeline.json",
|
||||
],
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts.verify_cleanup",
|
||||
"verify",
|
||||
"--seed",
|
||||
"evidence/clean-gc-seed.json",
|
||||
"--output",
|
||||
"evidence/clean-cleanup.json",
|
||||
],
|
||||
]:
|
||||
run(command_args, cwd=clone, env=env)
|
||||
receipt["pipeline"] = json.loads(
|
||||
(clone / "evidence/clean-pipeline.json").read_text()
|
||||
)
|
||||
receipt["cleanup"] = json.loads(
|
||||
(clone / "evidence/clean-cleanup.json").read_text()
|
||||
)
|
||||
receipt["cluster"] = json.loads(
|
||||
(clone / "evidence/clean-cluster.json").read_text()
|
||||
)
|
||||
import hashlib
|
||||
|
||||
expected = {
|
||||
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in (clone / "src").glob("*.py")
|
||||
}
|
||||
ids = run(
|
||||
["docker", "compose", "ps", "-q", "api"], cwd=clone, env=env
|
||||
).split()
|
||||
assert len(ids) == 2
|
||||
code = (
|
||||
"import hashlib,json,pathlib; print(json.dumps({p.name:"
|
||||
"hashlib.sha256(p.read_bytes()).hexdigest() for p in pathlib.Path('/app/src').glob('*.py')}))"
|
||||
)
|
||||
ids += run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"ps",
|
||||
"-q",
|
||||
"worker",
|
||||
"relay",
|
||||
"reconciler",
|
||||
"controller",
|
||||
"observer",
|
||||
],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
).split()
|
||||
assert len(ids) == 7
|
||||
for cid in ids:
|
||||
actual = json.loads(
|
||||
run(
|
||||
["docker", "exec", cid, "python", "-c", code],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
)
|
||||
assert actual == expected
|
||||
info = json.loads(
|
||||
run(["docker", "inspect", cid], cwd=clone, env=env)
|
||||
)[0]
|
||||
assert (
|
||||
info["Config"]["Labels"][
|
||||
"org.opencontainers.image.revision"
|
||||
]
|
||||
== sha
|
||||
)
|
||||
assert not info["HostConfig"]["PortBindings"]
|
||||
receipt[
|
||||
"all_seven_application_roles_runtime_hashes_and_revision_match"
|
||||
] = True
|
||||
receipt["fsck"] = run(
|
||||
["git", "fsck", "--full"], cwd=clone, env=env
|
||||
)
|
||||
receipt["checks_completed"] = True
|
||||
finally:
|
||||
assert project.startswith("mtusi-lab6-clean-")
|
||||
run(
|
||||
["docker", "compose", "down", "--volumes", "--remove-orphans"],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
receipt["result"] = "PASS"
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n")
|
||||
print(
|
||||
"PASS: fresh clone, build, HTTP tests, failover, rolling, persistence and runtime hashes"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Real S3 retention test: seed is separate from verification output."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
||||
from scripts.verify_pipeline import inside, operator, wait
|
||||
|
||||
|
||||
def seed(path):
|
||||
if path.exists():
|
||||
raise ValueError("Choose a new seed file")
|
||||
ready()
|
||||
compose("stop", "--timeout", "1", "reconciler")
|
||||
raw = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
with httpx.Client(base_url=BASE, trust_env=False, timeout=20) as c:
|
||||
user, _, session = actor(c)
|
||||
headers = auth(session)
|
||||
result = c.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers,
|
||||
json={
|
||||
"title": "Cleanup synthetic seed",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
assert result.status_code == 201
|
||||
chat = result.json()["id"]
|
||||
r = c.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
headers={**headers, "Content-Type": "image/png"},
|
||||
params={"filename": "retained.png"},
|
||||
content=raw,
|
||||
)
|
||||
assert r.status_code == 202
|
||||
attachment = r.json()["id"]
|
||||
wait(
|
||||
lambda: (
|
||||
c.get(
|
||||
"/api/v1/attachments/" + attachment, headers=headers
|
||||
).json()["status"]
|
||||
== "ready"
|
||||
)
|
||||
)
|
||||
job = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT id FROM jobs WHERE attachment_id=%s',({attachment!r},)).fetchone()\nprint(json.dumps(str(r['id'])))"
|
||||
)
|
||||
data = {
|
||||
"seed_id": uuid4().hex,
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"date": datetime.now(timezone.utc).isoformat(),
|
||||
"ready_attachment": attachment,
|
||||
"ready_job": job,
|
||||
"chat": chat,
|
||||
"owner": user["id"],
|
||||
}
|
||||
# Real old v1 objects will become obsolete after v2 is ready.
|
||||
second = operator(job, version=2)
|
||||
wait(
|
||||
lambda: inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT state FROM jobs WHERE id=%s',({second!r},)).fetchone()\nprint(json.dumps(r['state']=='ready'))"
|
||||
)
|
||||
)
|
||||
data["version2_job"] = second
|
||||
data["orphan"] = f"objects/cleanup-{data['seed_id']}/old-orphan"
|
||||
data["failed_id"] = str(uuid4())
|
||||
data["active_id"] = str(uuid4())
|
||||
data["reservation_id"] = str(uuid4())
|
||||
data["expired_reservation_id"] = str(uuid4())
|
||||
data["failed_source"] = f"objects/staging/{data['failed_id']}/original"
|
||||
data["active_source"] = f"objects/staging/{data['active_id']}/original"
|
||||
data["reservation_key"] = (
|
||||
f"objects/staging/{data['reservation_id']}/original"
|
||||
)
|
||||
data["expired_reservation_key"] = (
|
||||
f"objects/staging/{data['expired_reservation_id']}/original"
|
||||
)
|
||||
inside(f"""from pathlib import Path
|
||||
raw=Path('/app/src/__init__.py').read_bytes() or b'fixture'
|
||||
keys={json.dumps([data[k] for k in ["orphan", "failed_source", "active_source", "reservation_key", "expired_reservation_key"]])}
|
||||
for key in keys: store.put(key=key,stream=io.BytesIO(raw),size=len(raw),content_type='image/png',sha256=hashlib.sha256(raw).hexdigest())
|
||||
with db.connection() as c, c.transaction():
|
||||
for identity,state in [({data["failed_id"]!r},'failed'),({data["active_id"]!r},'processing')]:
|
||||
key='objects/staging/'+identity+'/original'
|
||||
c.execute(\"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,state,error_code,uploader_instance,expires_at) VALUES(%s,%s,%s,'synthetic.png','image/png',%s,%s,%s,%s,%s,'cleanup-fixture',clock_timestamp())\",(identity,{chat!r},{user["id"]!r},len(raw),hashlib.sha256(raw).hexdigest(),key,state,'invalid_image' if state=='failed' else None))
|
||||
c.execute(\"INSERT INTO jobs(id,attachment_id,pipeline_version,source_key,state,attempt,lease_until,updated_at,error_code) VALUES(%s,%s,1,%s,%s,1,clock_timestamp()+interval '1 hour',clock_timestamp()-interval '2 days',%s)\",(uuid4(),identity,key,state,'invalid_image' if state=='failed' else None))
|
||||
c.execute(\"INSERT INTO upload_reservations(id,object_key,expires_at) VALUES(%s,%s,clock_timestamp()+interval '1 hour'),(%s,%s,clock_timestamp()-interval '1 second')\",({data["reservation_id"]!r},{data["reservation_key"]!r},{data["expired_reservation_id"]!r},{data["expired_reservation_key"]!r}))
|
||||
print('true')""")
|
||||
data["seeded_unix"] = time.time()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
print(
|
||||
"PASS: retention seed created; real S3 age must reach300s", flush=True
|
||||
)
|
||||
|
||||
|
||||
def verify(seed_path, output):
|
||||
if output.exists():
|
||||
raise ValueError("Choose a new output path")
|
||||
data = json.loads(seed_path.read_text())
|
||||
report = {
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"seed": seed_path.name,
|
||||
"complete": False,
|
||||
}
|
||||
try:
|
||||
compose("stop", "--timeout", "1", "reconciler")
|
||||
|
||||
def age():
|
||||
return inside(
|
||||
f"h=store.head(key={data['orphan']!r})\nassert h is not None\nwith db.connection() as c: now=c.execute('SELECT clock_timestamp() now').fetchone()['now']\nprint(json.dumps((now-h.last_modified).total_seconds()))"
|
||||
)
|
||||
|
||||
while age() < 302:
|
||||
time.sleep(min(5, 303 - age()))
|
||||
report["real_s3_age_seconds"] = age()
|
||||
fresh = f"objects/cleanup-{data['seed_id']}/fresh-orphan"
|
||||
inside(
|
||||
f"b=b'fresh'\nstore.put(key={fresh!r},stream=io.BytesIO(b),size=len(b),content_type='image/png',sha256=hashlib.sha256(b).hexdigest())\nprint('true')"
|
||||
)
|
||||
oldkeys = [
|
||||
data["orphan"],
|
||||
data["failed_source"],
|
||||
data["expired_reservation_key"],
|
||||
] + [
|
||||
f"objects/{data['ready_attachment']}/v1/{v}"
|
||||
for v in ["original", "thumbnail", "crop", "optimized"]
|
||||
]
|
||||
protected = [data["active_source"], data["reservation_key"], fresh] + [
|
||||
f"objects/{data['ready_attachment']}/v2/{v}"
|
||||
for v in ["original", "thumbnail", "crop", "optimized"]
|
||||
]
|
||||
before = inside(
|
||||
f"print(json.dumps({{k:store.head(key=k) is not None for k in {oldkeys + protected!r}}}))"
|
||||
)
|
||||
assert all(before.values())
|
||||
dry = inside(
|
||||
"print(json.dumps(reconcile(db,store,apply=False,grace=300)))"
|
||||
)
|
||||
candidates = {a["key"] for a in dry["actions"]}
|
||||
assert set(oldkeys) <= candidates and not set(protected) & candidates
|
||||
afterdry = inside(
|
||||
f"print(json.dumps({{k:store.head(key=k) is not None for k in {oldkeys + protected!r}}}))"
|
||||
)
|
||||
assert afterdry == before
|
||||
applied = inside(
|
||||
"print(json.dumps(reconcile(db,store,apply=True,grace=300)))"
|
||||
)
|
||||
repeat = inside(
|
||||
"print(json.dumps(reconcile(db,store,apply=True,grace=300)))"
|
||||
)
|
||||
assert not repeat["actions"]
|
||||
after = inside(
|
||||
f"print(json.dumps({{k:store.head(key=k) is not None for k in {oldkeys + protected!r}}}))"
|
||||
)
|
||||
assert all(not after[k] for k in oldkeys) and all(
|
||||
after[k] for k in protected
|
||||
)
|
||||
failed = inside(
|
||||
f"with db.connection() as c: j=c.execute('SELECT id,error_code FROM jobs WHERE attachment_id=%s',({data['failed_id']!r},)).fetchone()\nprint(json.dumps(j,default=str))"
|
||||
)
|
||||
assert failed["error_code"] == "source_expired"
|
||||
try:
|
||||
operator(failed["id"])
|
||||
except RuntimeError:
|
||||
replay_refused = True
|
||||
else:
|
||||
raise AssertionError("Expired source replay must fail")
|
||||
# Expired reservation was removed, so a delayed API cannot commit its handoff.
|
||||
fenced = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM upload_reservations WHERE id=%s AND expires_at>clock_timestamp()',({data['expired_reservation_id']!r},)).fetchone()\nprint(json.dumps(r['n']==0))"
|
||||
)
|
||||
assert fenced
|
||||
report.update(
|
||||
dry_run=dry,
|
||||
apply=applied,
|
||||
repeat=repeat,
|
||||
before=before,
|
||||
after=after,
|
||||
dry_run_unchanged=True,
|
||||
active_current_and_fresh_protected=True,
|
||||
expired_source_replay_refused=replay_refused,
|
||||
expired_writer_fenced=fenced,
|
||||
complete=True,
|
||||
)
|
||||
finally:
|
||||
# Remove only this fixture's artificial active reservation/job; never real jobs.
|
||||
inside(
|
||||
f"with db.connection() as c, c.transaction():\n c.execute(\"UPDATE jobs SET state='failed',error_code='fixture_complete',lease_until=NULL WHERE attachment_id=%s\",({data['active_id']!r},))\n c.execute(\"UPDATE attachments SET state='failed',error_code='fixture_complete' WHERE id=%s\",({data['active_id']!r},))\n c.execute('DELETE FROM upload_reservations WHERE id=%s',({data['reservation_id']!r},))\nprint('true')"
|
||||
)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "reconciler")
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: real retention, dry-run/apply/repeat, current/active/fresh protection",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("action", choices=["seed", "verify"])
|
||||
p.add_argument("--seed", required=True, type=Path)
|
||||
p.add_argument("--output", type=Path)
|
||||
a = p.parse_args()
|
||||
if a.action == "seed":
|
||||
seed(a.seed)
|
||||
else:
|
||||
if a.output is None:
|
||||
p.error("output required")
|
||||
verify(a.seed, a.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,347 @@
|
||||
"""Проверки реальных процессов, failover, rolling и общей идемпотентности."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
|
||||
from scripts import cluster
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = compose("ps", "-q").split()
|
||||
result = []
|
||||
for c in json.loads(command(["docker", "inspect", *ids])):
|
||||
role = c["Config"]["Labels"]["com.docker.compose.service"]
|
||||
entry = {
|
||||
"role": role,
|
||||
"container": c["Id"][:12],
|
||||
"pid": c["State"]["Pid"],
|
||||
"started_at": c["State"]["StartedAt"],
|
||||
"ports": c["HostConfig"]["PortBindings"],
|
||||
"cpu_nano": c["HostConfig"]["NanoCpus"],
|
||||
"memory_limit": c["HostConfig"]["Memory"],
|
||||
}
|
||||
if role == "api":
|
||||
entry["instance"] = cluster.alias(c["Id"])
|
||||
assert not entry["ports"]
|
||||
result.append(entry)
|
||||
return result
|
||||
|
||||
|
||||
def exercise(client, session, chat, action, *, seconds=15):
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
observations, confirmed, errors, reads = [], {}, 0, 0
|
||||
started = time.monotonic()
|
||||
finished = threading.Event()
|
||||
action_result = {}
|
||||
|
||||
def operate():
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
action()
|
||||
except BaseException as exc:
|
||||
action_result["error"] = type(exc).__name__
|
||||
finally:
|
||||
action_result["finished"] = round(time.monotonic() - started, 3)
|
||||
finished.set()
|
||||
|
||||
thread = threading.Thread(target=operate)
|
||||
thread.start()
|
||||
key = uuid4().hex
|
||||
try:
|
||||
while (
|
||||
time.monotonic() - started < seconds
|
||||
or not finished.is_set()
|
||||
or time.monotonic() - started
|
||||
< action_result.get("finished", 0) + 2
|
||||
):
|
||||
h = {**auth(session), "Idempotency-Key": key}
|
||||
try:
|
||||
r = client.post(path, headers=h, json={"text": key})
|
||||
if r.status_code != 201:
|
||||
errors += 1
|
||||
continue
|
||||
m = r.json()
|
||||
confirmed[m["id"]] = m
|
||||
observations.append(
|
||||
{
|
||||
"at": round(time.monotonic() - started, 3),
|
||||
"instance": r.headers["x-instance-id"],
|
||||
}
|
||||
)
|
||||
key = uuid4().hex
|
||||
read = client.get(
|
||||
path, headers=auth(session), params={"limit": 100}
|
||||
)
|
||||
reads += read.status_code == 200
|
||||
errors += read.status_code != 200
|
||||
except httpx.HTTPError:
|
||||
errors += 1
|
||||
time.sleep(0.04)
|
||||
finally:
|
||||
thread.join(timeout=90)
|
||||
assert not action_result.get("error"), action_result
|
||||
found, cursor = [], None
|
||||
while True:
|
||||
r = client.get(
|
||||
path,
|
||||
headers=auth(session),
|
||||
params={"limit": 100, **({"cursor": cursor} if cursor else {})},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
page = r.json()
|
||||
found.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
by_id = {m["id"]: m for m in found}
|
||||
assert all(by_id.get(k) == v for k, v in confirmed.items())
|
||||
texts = [m["text"] for m in found]
|
||||
assert len(texts) == len(set(texts))
|
||||
recovery = next(
|
||||
(
|
||||
x["at"]
|
||||
for x in observations
|
||||
if x["at"] >= action_result["finished"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
assert recovery is not None and (seconds > 20 or recovery <= 10)
|
||||
elapsed = time.monotonic() - started
|
||||
return {
|
||||
"confirmed_writes": len(confirmed),
|
||||
"successful_reads": reads,
|
||||
"errors": errors,
|
||||
"successful_rps": round((len(confirmed) + reads) / elapsed, 2),
|
||||
"first_success_after_action_seconds": recovery,
|
||||
"action": action_result,
|
||||
"observations": observations,
|
||||
"confirmed_preserved": True,
|
||||
"duplicate_texts": False,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/cluster-repeat.json")
|
||||
args = parser.parse_args()
|
||||
report = {
|
||||
"date": datetime.now(timezone.utc).isoformat(),
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"complete": False,
|
||||
}
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
ready()
|
||||
initial = snapshot()
|
||||
apis = [c for c in initial if c["role"] == "api"]
|
||||
assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2
|
||||
report["before"] = initial
|
||||
with httpx.Client(base_url=BASE, trust_env=False, timeout=8) as client:
|
||||
user, _, session = actor(client)
|
||||
r = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=auth(session),
|
||||
json={
|
||||
"title": "Cluster verification",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
chat = r.json()
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
key = uuid4().hex
|
||||
|
||||
def repeat(_):
|
||||
with httpx.Client(
|
||||
base_url=BASE, trust_env=False, timeout=8
|
||||
) as c:
|
||||
r = c.post(
|
||||
path,
|
||||
headers={**auth(session), "Idempotency-Key": key},
|
||||
json={"text": "Same concurrent request"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
return r.json(), r.headers["x-instance-id"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
repeated = list(pool.map(repeat, range(30)))
|
||||
assert len({m[0]["id"] for m in repeated}) == 1
|
||||
assert len({m[1] for m in repeated}) == 2
|
||||
report["parallel_replay"] = {
|
||||
"requests": 30,
|
||||
"messages": 1,
|
||||
"instances": sorted({m[1] for m in repeated}),
|
||||
}
|
||||
# Сбой второй записи транзакции не должен оставить сообщение.
|
||||
fault_key = uuid4().hex
|
||||
fault_text = "Atomic rollback " + fault_key
|
||||
sql(
|
||||
"CREATE FUNCTION student_idempo_fault() RETURNS trigger "
|
||||
"LANGUAGE plpgsql AS $$ BEGIN IF NEW.key='"
|
||||
+ fault_key
|
||||
+ "' THEN RAISE EXCEPTION 'synthetic'; END IF; RETURN NEW; END $$; "
|
||||
"CREATE TRIGGER student_idempo_fault BEFORE INSERT ON idempotency "
|
||||
"FOR EACH ROW EXECUTE FUNCTION student_idempo_fault()"
|
||||
)
|
||||
try:
|
||||
failed = client.post(
|
||||
path,
|
||||
headers={**auth(session), "Idempotency-Key": fault_key},
|
||||
json={"text": fault_text},
|
||||
)
|
||||
assert failed.status_code == 500
|
||||
assert (
|
||||
sql(
|
||||
"SELECT count(*) FROM messages WHERE text='"
|
||||
+ fault_text
|
||||
+ "'"
|
||||
)
|
||||
== "0"
|
||||
)
|
||||
finally:
|
||||
sql(
|
||||
"DROP TRIGGER student_idempo_fault ON idempotency; "
|
||||
"DROP FUNCTION student_idempo_fault()"
|
||||
)
|
||||
retried = client.post(
|
||||
path,
|
||||
headers={**auth(session), "Idempotency-Key": fault_key},
|
||||
json={"text": fault_text},
|
||||
)
|
||||
assert retried.status_code == 201
|
||||
report["atomic_rollback_and_5xx_retry"] = True
|
||||
sql(
|
||||
"UPDATE idempotency SET expires_at=clock_timestamp()-interval '1 second' "
|
||||
"WHERE key='" + fault_key + "'"
|
||||
)
|
||||
expired = client.post(
|
||||
path,
|
||||
headers={**auth(session), "Idempotency-Key": fault_key},
|
||||
json={"text": "New retention window"},
|
||||
)
|
||||
assert expired.status_code == 201
|
||||
assert expired.json()["id"] != retried.json()["id"]
|
||||
report["expired_key_can_be_reused"] = True
|
||||
# Отдельный чат каждой серии: проверки дубликатов не смешивают тексты.
|
||||
report["failovers"] = []
|
||||
for api in apis:
|
||||
|
||||
def stop(target=api["instance"]):
|
||||
env = {**os.environ, "TARGET_INSTANCE_ID": target}
|
||||
subprocess.run(
|
||||
["scripts/stop-one.sh"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
r = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=auth(session),
|
||||
json={"title": "Failover", "member_ids": [user["id"]]},
|
||||
)
|
||||
result = exercise(client, session, r.json(), stop)
|
||||
assert api["instance"] not in [
|
||||
o["instance"] for o in result["observations"][-5:]
|
||||
]
|
||||
assert (
|
||||
command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{.State.Running}}",
|
||||
api["container"],
|
||||
]
|
||||
)
|
||||
== "false"
|
||||
)
|
||||
result["stopped"] = api
|
||||
report["failovers"].append(result)
|
||||
compose("up", "-d", "--no-build", "--wait")
|
||||
ready()
|
||||
r = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=auth(session),
|
||||
json={"title": "Rolling", "member_ids": [user["id"]]},
|
||||
)
|
||||
before_roll = snapshot()
|
||||
report["rolling"] = exercise(
|
||||
client,
|
||||
session,
|
||||
r.json(),
|
||||
lambda: command(["scripts/rolling-update.sh"]),
|
||||
seconds=45,
|
||||
)
|
||||
after_roll = snapshot()
|
||||
assert not (
|
||||
{c["container"] for c in before_roll if c["role"] == "api"}
|
||||
& {c["container"] for c in after_roll if c["role"] == "api"}
|
||||
)
|
||||
report["rolling"]["before"] = before_roll
|
||||
report["rolling"]["after"] = after_roll
|
||||
replay = repeat(0)[0]
|
||||
assert replay == repeated[0][0]
|
||||
report["replay_after_replacement"] = True
|
||||
before = snapshot()
|
||||
env = {
|
||||
**os.environ,
|
||||
"NO_PROXY": "localhost,127.0.0.1",
|
||||
"no_proxy": "localhost,127.0.0.1",
|
||||
}
|
||||
for mode, hook in [
|
||||
("failover", "scripts/stop-one.sh"),
|
||||
("persistence", "scripts/restart.sh"),
|
||||
]:
|
||||
if mode == "persistence":
|
||||
compose("up", "-d", "--no-build", "--wait")
|
||||
ready()
|
||||
before = snapshot()
|
||||
run = subprocess.run(
|
||||
[
|
||||
".venv/bin/python",
|
||||
"tests/resilience.py",
|
||||
"--mode",
|
||||
mode,
|
||||
"--action-script",
|
||||
hook,
|
||||
"--base-url",
|
||||
BASE,
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert run.returncode == 0, run.stdout + run.stderr
|
||||
report["public_" + mode] = run.stdout.strip()
|
||||
after = snapshot()
|
||||
for role in ["postgres", "cache", "s3", "broker", "lb"]:
|
||||
old = next(c for c in before if c["role"] == role)
|
||||
new = next(c for c in after if c["role"] == role)
|
||||
assert old["started_at"] != new["started_at"]
|
||||
report["after_persistence"] = after
|
||||
report["complete"] = True
|
||||
finally:
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print("PASS: process failover, rolling, replay and full persistence")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Restart actual stores and compare data accepted before the restart."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
|
||||
os.environ.setdefault("COMPOSE_FILE", "compose.yaml:compose.test.yaml")
|
||||
from scripts.observe import fetch, logs, query, spans, wait
|
||||
from scripts.stand import ROOT, command, compose
|
||||
|
||||
|
||||
def instances():
|
||||
result = {}
|
||||
for role in ["prometheus", "loki", "tempo", "grafana"]:
|
||||
cid = compose("ps", "-q", role)
|
||||
data = json.loads(command(["docker", "inspect", cid]))[0]
|
||||
result[role] = {
|
||||
"started_at": data["State"]["StartedAt"],
|
||||
"volumes": sorted(
|
||||
m["Name"] for m in data["Mounts"] if m["Type"] == "volume"
|
||||
),
|
||||
"read_only": data["HostConfig"]["ReadonlyRootfs"],
|
||||
"cap_drop": data["HostConfig"]["CapDrop"],
|
||||
"user": data["Config"]["User"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--causal-evidence", default="evidence/telemetry-first.json"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", default="evidence/observability-persistence-first.json"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists()
|
||||
causal = json.loads((ROOT / args.causal_evidence).read_text())
|
||||
assert causal["complete"]
|
||||
identity = causal["causal_uploads"][0]["trace_id"]
|
||||
timestamp = time.time() - 20
|
||||
historical = query("sum(messenger_http_requests_total)", at=timestamp)
|
||||
assert historical and spans(identity) and logs(identity)["data"]["result"]
|
||||
report = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"trace_id": identity,
|
||||
"historical_query_at": timestamp,
|
||||
"historical_before": historical,
|
||||
"before": instances(),
|
||||
"complete": False,
|
||||
}
|
||||
password = (ROOT / "secrets/grafana_password").read_text().strip()
|
||||
base = "http://127.0.0.1:" + os.getenv("GRAFANA_PORT", "3006")
|
||||
with httpx.Client(
|
||||
base_url=base, auth=("admin", password), timeout=10, trust_env=False
|
||||
) as grafana:
|
||||
preferences = grafana.get("/api/user/preferences")
|
||||
preferences.raise_for_status()
|
||||
previous = preferences.json()
|
||||
temporary = {
|
||||
**previous,
|
||||
"theme": "light" if previous.get("theme") != "light" else "dark",
|
||||
}
|
||||
try:
|
||||
changed = grafana.put("/api/user/preferences", json=temporary)
|
||||
changed.raise_for_status()
|
||||
compose("restart", "prometheus", "loki", "tempo", "grafana")
|
||||
for role, path in [
|
||||
("prometheus", "/-/ready"),
|
||||
("loki", "/ready"),
|
||||
("tempo", "/ready"),
|
||||
]:
|
||||
wait(
|
||||
lambda role=role, path=path: fetch(
|
||||
role, path, json_result=False
|
||||
),
|
||||
timeout=120,
|
||||
)
|
||||
|
||||
def grafana_ready():
|
||||
try:
|
||||
response = grafana.get("/api/health")
|
||||
return (
|
||||
response.status_code == 200
|
||||
and response.json()["database"] == "ok"
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
return False
|
||||
|
||||
wait(grafana_ready, timeout=120)
|
||||
wait(lambda: spans(identity), timeout=120)
|
||||
wait(lambda: logs(identity)["data"]["result"], timeout=120)
|
||||
report["historical_after"] = query(
|
||||
"sum(messenger_http_requests_total)", at=timestamp
|
||||
)
|
||||
assert report["historical_after"] == historical
|
||||
assert (
|
||||
grafana.get("/api/user/preferences").json()["theme"]
|
||||
== temporary["theme"]
|
||||
)
|
||||
report["after"] = instances()
|
||||
for role, before in report["before"].items():
|
||||
after = report["after"][role]
|
||||
assert before["started_at"] != after["started_at"]
|
||||
assert (
|
||||
before["volumes"] == after["volumes"] and before["volumes"]
|
||||
)
|
||||
assert after["read_only"] and after["user"] not in {
|
||||
"",
|
||||
"0",
|
||||
"0:0",
|
||||
"root",
|
||||
}
|
||||
assert "ALL" in after["cap_drop"]
|
||||
report.update(
|
||||
stored_trace_survives=True,
|
||||
stored_logs_survive=True,
|
||||
historical_metric_survives=True,
|
||||
grafana_sqlite_preference_survives=True,
|
||||
complete=True,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
grafana.put(
|
||||
"/api/user/preferences", json=previous
|
||||
).raise_for_status()
|
||||
finally:
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: metrics, traces, logs and Grafana state survive real store restarts"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,687 @@
|
||||
"""Repeatable fault injection for grade 5, track 2; synthetic data only."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
os.environ.setdefault("COMPOSE_FILE", "compose.yaml:compose.test.yaml")
|
||||
os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
|
||||
os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
||||
|
||||
PREFIX = """import io,json,hashlib,time,urllib.request
|
||||
from uuid import UUID,uuid4
|
||||
from psycopg.types.json import Jsonb
|
||||
from src.pipeline import database,broker,envelope,STREAM,GROUP
|
||||
from src.object_store import ObjectStore,BUCKET
|
||||
from src.operator import change
|
||||
from src.reconcile import reconcile
|
||||
db,store,queue=database(),ObjectStore(),broker()
|
||||
"""
|
||||
|
||||
|
||||
def inside(code):
|
||||
cid = compose("ps", "-q", "controller").split()[0]
|
||||
return json.loads(
|
||||
command(
|
||||
["docker", "exec", "-i", cid, "python", "-"], input=PREFIX + code
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def wait(fn, timeout=90):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
value = fn()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.15)
|
||||
raise TimeoutError("Fault scenario condition not reached")
|
||||
|
||||
|
||||
def stop(role):
|
||||
compose("stop", "--timeout", "1", role)
|
||||
|
||||
|
||||
def start(role):
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", role)
|
||||
|
||||
|
||||
def row(job):
|
||||
return inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT * FROM jobs WHERE id=%s',({job!r},)).fetchone()\nprint(json.dumps(r,default=str))"
|
||||
)
|
||||
|
||||
|
||||
def inject(job, phase, action, remaining=1):
|
||||
return inside(
|
||||
f"with db.connection() as c: r=c.execute('INSERT INTO pipeline_faults(target,phase,action,remaining) VALUES(%s,%s,%s,%s) RETURNING id',({job!r},{phase!r},{action!r},{remaining})).fetchone()\nprint(json.dumps(r['id']))"
|
||||
)
|
||||
|
||||
|
||||
def hit(identity):
|
||||
return inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT hit_at IS NOT NULL hit FROM pipeline_faults WHERE id=%s',({identity},)).fetchone()\nprint(json.dumps(r['hit']))"
|
||||
)
|
||||
|
||||
|
||||
def operator(job, version=None):
|
||||
return inside(
|
||||
f"print(json.dumps(change(db,store,job_id=UUID({job!r}),operator='synthetic-verifier',reason='Explicit fault matrix replay',version={version!r})))"
|
||||
)
|
||||
|
||||
|
||||
def duplicate(job, count=5):
|
||||
return inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT * FROM jobs WHERE id=%s',({job!r},)).fetchone()\ne=envelope(r)\nids=[queue.xadd(STREAM,{{'job':json.dumps(e)}}) for _ in range({count})]\nprint(json.dumps(ids))"
|
||||
)
|
||||
|
||||
|
||||
def inspect_effect(job, *, pending=False):
|
||||
return inside(f"""with db.connection() as c:
|
||||
j=c.execute('SELECT * FROM jobs WHERE id=%s',({job!r},)).fetchone()
|
||||
v=c.execute('SELECT name,object_key,sha256,size_bytes FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s ORDER BY name',(j['attachment_id'],j['pipeline_version'])).fetchall()
|
||||
p=c.execute('SELECT count(*) n FROM effect_publications WHERE attachment_id=%s AND pipeline_version=%s',(j['attachment_id'],j['pipeline_version'])).fetchone()['n']
|
||||
e=c.execute('SELECT event,detail,created_at FROM pipeline_events WHERE job_id=%s ORDER BY id',({job!r},)).fetchall()
|
||||
keys=[o.object_name for o in store.objects() if o.object_name.startswith(f"objects/{{j['attachment_id']}}/v{{j['pipeline_version']}}/")]
|
||||
pending_entries=[]
|
||||
if {pending!r}:
|
||||
for item in queue.xpending_range(STREAM,GROUP,'-','+',1000):
|
||||
entry=item['message_id']
|
||||
messages=queue.xrange(STREAM,min=entry,max=entry)
|
||||
if messages and json.loads(messages[0][1].get('job','{{}}')).get('job_id')==str(j['id']): pending_entries.append(entry)
|
||||
print(json.dumps({{'job':j,'variants':v,'publications':p,'physical_keys':keys,'events':e,'pending_stream_entries':pending_entries}},default=str))""")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/pipeline-repeat.json")
|
||||
parser.add_argument("--repeats", type=int, default=2)
|
||||
parser.add_argument(
|
||||
"--start-at", choices=["all", "versions"], default="all"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
if output.exists():
|
||||
raise ValueError("Choose a new output path")
|
||||
report = {
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"date": datetime.now(timezone.utc).isoformat(),
|
||||
"track": 2,
|
||||
"scope": args.start_at,
|
||||
"complete": False,
|
||||
"cases": [],
|
||||
}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def save(name, details):
|
||||
report["cases"].append({"case": name, **details})
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print("PASS:", name, flush=True)
|
||||
|
||||
try:
|
||||
ready()
|
||||
# Check instrumentation is really enabled and production default is off.
|
||||
cid = compose("ps", "-q", "api").split()[0]
|
||||
assert (
|
||||
command(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"python",
|
||||
"-c",
|
||||
"import os;print(os.getenv('PIPELINE_FAULTS'))",
|
||||
]
|
||||
)
|
||||
== "1"
|
||||
)
|
||||
stop("reconciler")
|
||||
with httpx.Client(
|
||||
base_url=BASE, trust_env=False, timeout=25
|
||||
) as client:
|
||||
user, _, session = actor(client)
|
||||
h = auth(session)
|
||||
c = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=h,
|
||||
json={
|
||||
"title": "Pipeline synthetic faults",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
assert c.status_code == 201
|
||||
chat = c.json()["id"]
|
||||
raw_io = io.BytesIO()
|
||||
Image.new("RGBA", (320, 200), (20, 50, 170, 120)).save(
|
||||
raw_io, format="PNG"
|
||||
)
|
||||
raw = raw_io.getvalue()
|
||||
|
||||
def upload():
|
||||
r = client.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
headers={**h, "Content-Type": "image/png"},
|
||||
params={"filename": "synthetic.png"},
|
||||
content=raw,
|
||||
)
|
||||
assert r.status_code == 202, r.text
|
||||
a = r.json()
|
||||
assert a["status"] == "queued" and not a["variants"]
|
||||
j = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT id FROM jobs WHERE attachment_id=%s',({a['id']!r},)).fetchone()\nprint(json.dumps(str(r['id'])))"
|
||||
)
|
||||
return a, j
|
||||
|
||||
def metadata(a):
|
||||
r = client.get("/api/v1/attachments/" + a["id"], headers=h)
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
def until(a, state="ready", timeout=90):
|
||||
return wait(
|
||||
lambda: (
|
||||
r if (r := metadata(a))["status"] == state else None
|
||||
),
|
||||
timeout,
|
||||
)
|
||||
|
||||
def confirm(a, j):
|
||||
until(a)
|
||||
downloaded = client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
)
|
||||
assert (
|
||||
downloaded.status_code == 200 and downloaded.content == raw
|
||||
)
|
||||
m = metadata(a)
|
||||
assert (
|
||||
m["sha256"] == hashlib.sha256(raw).hexdigest()
|
||||
and m["error_code"] is None
|
||||
)
|
||||
assert {v["name"] for v in m["variants"]} == {
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized",
|
||||
}
|
||||
for v in m["variants"]:
|
||||
r = client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content",
|
||||
headers=h,
|
||||
params={"variant": v["name"]},
|
||||
)
|
||||
assert (
|
||||
r.status_code == 200
|
||||
and hashlib.sha256(r.content).hexdigest()
|
||||
== v["sha256"]
|
||||
)
|
||||
with Image.open(io.BytesIO(r.content)) as image:
|
||||
assert (
|
||||
image.size
|
||||
== {
|
||||
"thumbnail": (256, 160),
|
||||
"crop": (128, 128),
|
||||
"optimized": (320, 200),
|
||||
}[v["name"]]
|
||||
)
|
||||
assert not image.getexif()
|
||||
effect = inspect_effect(j)
|
||||
assert (
|
||||
effect["publications"] == 1
|
||||
and len(effect["variants"]) == 4
|
||||
and len(effect["physical_keys"]) == 4
|
||||
)
|
||||
return effect
|
||||
|
||||
if args.start_at == "all":
|
||||
# Source-only crash before the DB handoff must never be reported as accepted.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
marker = inject(chat, "api_after_staging", "wait")
|
||||
before = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
pool = ThreadPoolExecutor(max_workers=1)
|
||||
future = pool.submit(
|
||||
lambda: client.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
headers={**h, "Content-Type": "image/png"},
|
||||
params={"filename": "unconfirmed.png"},
|
||||
content=raw,
|
||||
)
|
||||
)
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
compose("kill", "-s", "SIGKILL", "api")
|
||||
try:
|
||||
response = future.result(15)
|
||||
assert response.status_code != 202
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
pool.shutdown()
|
||||
start("api")
|
||||
ready()
|
||||
after = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
assert before == after
|
||||
save(
|
||||
"staging_before_handoff_crash",
|
||||
{
|
||||
"no_202": True,
|
||||
"no_attachment_or_job_created": True,
|
||||
"orphan_retained_for_cleanup": True,
|
||||
},
|
||||
)
|
||||
# API durable commit/outbox survives restart without a broker or worker.
|
||||
stop("broker")
|
||||
a, j = upload()
|
||||
linked = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert linked.status_code == 201
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
compose("restart", "api")
|
||||
ready()
|
||||
start("broker")
|
||||
start("relay")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
save(
|
||||
"commit_before_publish_and_worker_stopped",
|
||||
{
|
||||
"attachment": a["id"],
|
||||
"effect": effect,
|
||||
"queued_link_allowed": True,
|
||||
"api_and_broker_restarted": True,
|
||||
"broker_stopped_during_upload": True,
|
||||
},
|
||||
)
|
||||
# Broker-volume survival with a confirmed, still-unconsumed stream entry.
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
wait(
|
||||
lambda: inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NOT NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']>0))"
|
||||
)
|
||||
)
|
||||
stop("relay")
|
||||
ids = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
compose("kill", "-s", "SIGKILL", "broker")
|
||||
start("broker")
|
||||
wait(lambda: inside("print(json.dumps(queue.ping()))"))
|
||||
restored = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
assert restored == ids, {"before": ids, "after": restored}
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"confirmed_broker_entry_survives_sigkill",
|
||||
{
|
||||
"effect": confirm(a, j),
|
||||
"same_stream_entries": True,
|
||||
"entry_count": len(ids),
|
||||
},
|
||||
)
|
||||
# Confirm succeeded, PG marker did not: relay recovery may publish a duplicate.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
marker = inject(j, "relay_after_publish", "crash")
|
||||
start("relay")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
time.sleep(0.5)
|
||||
unpublished = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']))"
|
||||
)
|
||||
assert unpublished >= 1
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"relay_crash_after_xadd_before_pg_marker",
|
||||
{
|
||||
"unpublished_after_crash": unpublished,
|
||||
"effect": confirm(a, j),
|
||||
},
|
||||
)
|
||||
# Repeated before/after effect and commit/ack windows.
|
||||
for repeat in range(args.repeats):
|
||||
for phase in [
|
||||
"before_effect",
|
||||
"after_effect",
|
||||
"after_commit",
|
||||
]:
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, phase, "wait")
|
||||
start("worker")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
at_crash = inspect_effect(
|
||||
j, pending=phase == "after_commit"
|
||||
)
|
||||
assert at_crash["job"]["state"] == (
|
||||
"ready"
|
||||
if phase == "after_commit"
|
||||
else "processing"
|
||||
)
|
||||
assert at_crash["publications"] == (
|
||||
1 if phase == "after_commit" else 0
|
||||
)
|
||||
assert len(at_crash["physical_keys"]) == (
|
||||
0 if phase == "before_effect" else 4
|
||||
)
|
||||
if phase == "after_commit":
|
||||
assert at_crash["pending_stream_entries"], (
|
||||
"Result must be committed while notification is still unacknowledged"
|
||||
)
|
||||
assert not any(
|
||||
e["event"] == "child_finished"
|
||||
for e in at_crash["events"]
|
||||
)
|
||||
compose("kill", "-s", "SIGKILL", "worker")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
if phase == "after_commit":
|
||||
wait(
|
||||
lambda j=j: any(
|
||||
e["event"] == "duplicate_decision"
|
||||
and e["detail"]["state"] == "ready"
|
||||
for e in inspect_effect(j)["events"]
|
||||
)
|
||||
)
|
||||
wait(
|
||||
lambda j=j: inside(
|
||||
f"print(json.dumps(not any(json.loads(fields.get('job','{{}}')).get('job_id')=={j!r} for _,fields in queue.xrange(STREAM))))"
|
||||
)
|
||||
)
|
||||
effect = inspect_effect(j)
|
||||
else:
|
||||
assert effect["job"]["attempt"] >= 2
|
||||
save(
|
||||
f"{phase}_sigkill_repeat_{repeat + 1}",
|
||||
{"at_crash": at_crash, "effect": effect},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["attempt"] == 2
|
||||
save("transient_retry_with_jitter", {"effect": effect})
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, "before_effect", "hang")
|
||||
start("worker")
|
||||
wait(lambda: hit(marker))
|
||||
limits = inside(
|
||||
f"with db.connection() as c: r=c.execute(\"SELECT detail FROM pipeline_events WHERE job_id=%s AND event='worker_resource_limits' ORDER BY id DESC LIMIT 1\",({j!r},)).fetchone()\nprint(json.dumps(r['detail']))"
|
||||
)
|
||||
assert limits["address_space_bytes"] == [805306368, 805306368]
|
||||
assert limits["memory.max"] == "1610612736"
|
||||
effect = confirm(a, j)
|
||||
assert any(
|
||||
e["event"] == "retry"
|
||||
and e["detail"]["code"] == "worker_timeout"
|
||||
for e in effect["events"]
|
||||
)
|
||||
save(
|
||||
"hung_child_killed_and_retried",
|
||||
{"effect": effect, "observed_limits": limits},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "permanent")
|
||||
start("worker")
|
||||
failed = until(a, "failed")
|
||||
assert failed["error_code"] == "invalid_image"
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
r = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert r.status_code == 409
|
||||
assert operator(j) == j
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["cycle"] == 2
|
||||
try:
|
||||
operator(j)
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Replay of ready must be rejected")
|
||||
save(
|
||||
"permanent_failed_registry_and_audited_replay",
|
||||
{
|
||||
"failed": failed,
|
||||
"effect": effect,
|
||||
"ready_replay_rejected": True,
|
||||
},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient", remaining=5)
|
||||
start("worker")
|
||||
failed = until(a, "failed", timeout=150)
|
||||
assert (
|
||||
failed["error_code"] == "retry_exhausted"
|
||||
and row(j)["attempt"] == 5
|
||||
)
|
||||
operator(j)
|
||||
save(
|
||||
"finite_retry_exhaustion_then_explicit_replay",
|
||||
{"failed": failed, "effect": confirm(a, j)},
|
||||
)
|
||||
# Reverse notification order and add concurrent copies: one publication/key.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
b, k = upload()
|
||||
duplicate(k, 8)
|
||||
duplicate(j, 8)
|
||||
start("worker")
|
||||
start("relay")
|
||||
ea = confirm(a, j)
|
||||
confirm(b, k)
|
||||
duplicate(j, 10)
|
||||
duplicate(k, 10)
|
||||
wait(
|
||||
lambda: any(
|
||||
e["event"] == "duplicate_decision"
|
||||
for e in inspect_effect(j)["events"]
|
||||
)
|
||||
)
|
||||
assert (
|
||||
inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"]
|
||||
)
|
||||
save(
|
||||
"reordered_and_duplicate_notifications",
|
||||
{
|
||||
"effects": [inspect_effect(j), inspect_effect(k)],
|
||||
"added_duplicates": 36,
|
||||
"no_extra_attempt_after_ready": True,
|
||||
},
|
||||
)
|
||||
# Hold v1 after its PUTs, complete v2 on the other bounded slot, release old CAS.
|
||||
for repeat in range(args.repeats):
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, "after_effect", "wait")
|
||||
# Keep one controller process hot throughout the narrow stale-writer window.
|
||||
code = f"""from src.pipeline import event
|
||||
with db.connection() as c: event(c,UUID({j!r}),'version_controller_waiting')
|
||||
end=time.monotonic()+45
|
||||
while True:
|
||||
with db.connection() as c: hit=c.execute('SELECT hit_at FROM pipeline_faults WHERE id=%s',({marker},)).fetchone()['hit_at']
|
||||
if hit: break
|
||||
if time.monotonic()>end: raise TimeoutError('v1 hook never hit')
|
||||
time.sleep(.05)
|
||||
k=change(db,store,job_id=UUID({j!r}),operator='synthetic-verifier',reason='Held stale writer race',version=2)
|
||||
end=time.monotonic()+10
|
||||
while True:
|
||||
with db.connection() as c: ready=c.execute('SELECT state FROM jobs WHERE id=%s',(k,)).fetchone()['state']=='ready'
|
||||
if ready: break
|
||||
if time.monotonic()>end: raise TimeoutError('v2 did not finish inside live v1 budget')
|
||||
time.sleep(.05)
|
||||
with db.connection() as c:
|
||||
hashes=c.execute('SELECT name,sha256 FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=2 ORDER BY name',({a["id"]!r},)).fetchall()
|
||||
c.execute('UPDATE pipeline_faults SET released_at=clock_timestamp() WHERE id=%s',({marker},))
|
||||
end=time.monotonic()+10
|
||||
while True:
|
||||
with db.connection() as c: stale=c.execute("SELECT count(*) n FROM pipeline_events WHERE job_id=%s AND event='stale_completion_rejected'",({j!r},)).fetchone()['n']
|
||||
if stale: break
|
||||
if time.monotonic()>end: raise TimeoutError('Old completion was not rejected')
|
||||
time.sleep(.05)
|
||||
print(json.dumps({{'job_id':k,'hashes':{{r['name']:r['sha256'] for r in hashes}}}}))
|
||||
"""
|
||||
with ThreadPoolExecutor(max_workers=1) as hot:
|
||||
future = hot.submit(inside, code)
|
||||
wait(
|
||||
lambda j=j: inside(
|
||||
f"with db.connection() as c: n=c.execute(\"SELECT count(*) n FROM pipeline_events WHERE job_id=%s AND event='version_controller_waiting'\",({j!r},)).fetchone()['n']\nprint(json.dumps(n>0))"
|
||||
)
|
||||
)
|
||||
start("worker")
|
||||
race = future.result(timeout=45)
|
||||
k = race["job_id"]
|
||||
hashes = race["hashes"]
|
||||
confirm(a, k)
|
||||
duplicate(j, 12)
|
||||
wait(
|
||||
lambda j=j: any(
|
||||
e["event"] == "duplicate_decision"
|
||||
for e in inspect_effect(j)["events"]
|
||||
)
|
||||
)
|
||||
assert hashes == {
|
||||
v["name"]: v["sha256"] for v in confirm(a, k)["variants"]
|
||||
}
|
||||
assert inspect_effect(j)["publications"] == 0
|
||||
save(
|
||||
f"stale_v1_after_v2_repeat_{repeat + 1}",
|
||||
{
|
||||
"v1": inspect_effect(j),
|
||||
"v2": inspect_effect(k),
|
||||
"new_hashes_unchanged": True,
|
||||
},
|
||||
)
|
||||
# No arbitrary URL/bytes fields in queue envelopes.
|
||||
invalid = inside(
|
||||
"bad={'schema_version':1,'url':'http://example.invalid/raw'}\nqueue.xadd(STREAM,{'job':json.dumps(bad)})\nprint('true')"
|
||||
)
|
||||
assert invalid
|
||||
wait(
|
||||
lambda: inside(
|
||||
"with db.connection() as c: r=c.execute(\"SELECT count(*) n FROM pipeline_events WHERE event='invalid_envelope'\").fetchone()\nprint(json.dumps(r['n']>0))"
|
||||
)
|
||||
)
|
||||
save(
|
||||
"malformed_notification_rejected", {"durable_diagnostic": True}
|
||||
)
|
||||
# Private bucket, bounded IAM, and download after uploader process dies.
|
||||
a, j = upload()
|
||||
confirm(a, j)
|
||||
key = f"objects/{a['id']}/v1/original"
|
||||
security = inside(f"""from minio.error import S3Error
|
||||
from urllib.error import HTTPError
|
||||
try: urllib.request.urlopen('http://s3:9000/'+BUCKET+'/' + {key!r},timeout=3)
|
||||
except HTTPError as e: anonymous=e.code
|
||||
else: raise AssertionError('Anonymous access allowed')
|
||||
denials={{}}
|
||||
for name,fn in [('create_bucket',lambda:store.client.make_bucket('forbidden-'+uuid4().hex)),('write_outside_prefix',lambda:store.client.put_object(BUCKET,'outside-'+uuid4().hex,io.BytesIO(b'x'),1)),('list_other_bucket',lambda:list(store.client.list_objects('forbidden-'+uuid4().hex)))]:
|
||||
try: fn()
|
||||
except S3Error as e: denials[name]=e.code
|
||||
else: raise AssertionError('IAM allowed forbidden action')
|
||||
print(json.dumps({{'anonymous':anonymous,'iam':denials}}))""")
|
||||
assert security["anonymous"] == 403 and set(
|
||||
security["iam"].values()
|
||||
) == {"AccessDenied"}
|
||||
selected = None
|
||||
for cid in compose("ps", "-q", "api").split():
|
||||
alias = command(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])",
|
||||
]
|
||||
)
|
||||
uploader = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT uploader_instance FROM attachments WHERE id=%s',({a['id']!r},)).fetchone()\nprint(json.dumps(r['uploader_instance']))"
|
||||
)
|
||||
if alias == uploader:
|
||||
selected = cid
|
||||
assert selected
|
||||
command(["docker", "stop", "--time", "1", selected])
|
||||
ready()
|
||||
wait(
|
||||
lambda: (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 200
|
||||
)
|
||||
)
|
||||
downloaded = client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
)
|
||||
assert (
|
||||
downloaded.content == raw
|
||||
and downloaded.headers["X-Instance-Id"] != uploader
|
||||
)
|
||||
start("api")
|
||||
ready()
|
||||
save(
|
||||
"private_iam_and_other_api_download",
|
||||
{
|
||||
"security": security,
|
||||
"attachment": a["id"],
|
||||
"uploader": uploader,
|
||||
"downloader": downloaded.headers["X-Instance-Id"],
|
||||
"sha256": hashlib.sha256(raw).hexdigest(),
|
||||
},
|
||||
)
|
||||
report["worker_metrics"] = inside(
|
||||
"with db.connection() as c: r=c.execute(\"SELECT job_id,detail FROM pipeline_events WHERE event='child_finished' ORDER BY id\").fetchall()\nprint(json.dumps(r,default=str))"
|
||||
)
|
||||
report["audit"] = inside(
|
||||
"with db.connection() as c: r=c.execute('SELECT job_id,action,operator,reason,created_at FROM pipeline_audit ORDER BY id').fetchall()\nprint(json.dumps(r,default=str))"
|
||||
)
|
||||
report["complete"] = True
|
||||
finally:
|
||||
for role in ["api", "broker", "relay", "worker", "reconciler"]:
|
||||
try:
|
||||
start(role)
|
||||
except Exception:
|
||||
pass
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print("PASS: versioned pipeline scope=" + args.start_at, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Prepare public/negative fixtures and run the operator-only matrix probe."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from scripts.bootstrap_security import (
|
||||
SECRET,
|
||||
key_bytes,
|
||||
make_root,
|
||||
public,
|
||||
sign_leaf,
|
||||
write_private,
|
||||
)
|
||||
from scripts.stand import ROOT, command, compose
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", default="evidence/security-first.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists(), "Choose a new receipt path"
|
||||
fixture = SECRET / "probe"
|
||||
fixture.mkdir(mode=0o755, exist_ok=True)
|
||||
root_key, root_cert = make_root()
|
||||
key, leaf = sign_leaf(root_key, root_cert, "lb", ["lb"])
|
||||
write_private(fixture / "foreign-ca.pem", public(root_cert), mode=0o644)
|
||||
write_private(
|
||||
fixture / "foreign/cert.pem",
|
||||
public(leaf) + public(root_cert),
|
||||
mode=0o644,
|
||||
)
|
||||
write_private(fixture / "foreign/key.pem", key_bytes(key), mode=0o644)
|
||||
result = json.loads(
|
||||
compose(
|
||||
"--profile",
|
||||
"operator",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"operator-probe",
|
||||
)
|
||||
)
|
||||
result.update(
|
||||
date=datetime.now(UTC).isoformat(),
|
||||
source_commit=command(["git", "rev-parse", "HEAD"]),
|
||||
)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
assert result["complete"]
|
||||
print(
|
||||
"PASS: real mTLS identities, server CA/hostname, closed plaintext boundaries and worker least privilege"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,340 @@
|
||||
"""Actual API-to-worker causality, log correlation, provisioning and privacy."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
os.environ.setdefault("COMPOSE_FILE", "compose.yaml:compose.test.yaml")
|
||||
from scripts.observe import fetch, logs, query, spans, wait
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
||||
|
||||
|
||||
def verify_chain(items, trace_id, *, retry):
|
||||
assert items and {s["trace_id"] for s in items} == {trace_id}
|
||||
by_id = {s["span_id"]: s for s in items}
|
||||
producers = [s for s in items if s["kind"] == "SPAN_KIND_PRODUCER"]
|
||||
consumers = [s for s in items if s["kind"] == "SPAN_KIND_CONSUMER"]
|
||||
processing = [s for s in items if s["name"] == "attachment.process"]
|
||||
assert producers and consumers and processing
|
||||
assert {s["service"] for s in items} >= {
|
||||
"messenger-api",
|
||||
"messenger-relay",
|
||||
"messenger-worker",
|
||||
}
|
||||
for consumer in consumers:
|
||||
assert (
|
||||
by_id[consumer["parent_span_id"]]["kind"] == "SPAN_KIND_PRODUCER"
|
||||
)
|
||||
for process in processing:
|
||||
assert by_id[process["parent_span_id"]]["kind"] == "SPAN_KIND_CONSUMER"
|
||||
assert any(
|
||||
s["name"] == "s3.put" and s["service"] == "messenger-worker"
|
||||
for s in items
|
||||
)
|
||||
assert any(
|
||||
s["name"] == "db.postgresql" and s["service"] == "messenger-worker"
|
||||
for s in items
|
||||
)
|
||||
if retry:
|
||||
assert len(processing) >= 2
|
||||
assert any(
|
||||
s["status"].get("code") in {2, "STATUS_CODE_ERROR"}
|
||||
for s in processing
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/telemetry-first.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
assert not output.exists(), "Choose a new output path"
|
||||
report = {
|
||||
"date": datetime.now(UTC).isoformat(),
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"complete": False,
|
||||
}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
ready(timeout=90)
|
||||
for service, path in [
|
||||
("prometheus", "/-/ready"),
|
||||
("loki", "/ready"),
|
||||
("tempo", "/ready"),
|
||||
("otel", "/"),
|
||||
]:
|
||||
wait(lambda s=service, p=path: fetch(s, p, json_result=False))
|
||||
report["backends_ready"] = True
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (320, 200), (24, 110, 153)).save(buffer, "PNG")
|
||||
raw = buffer.getvalue()
|
||||
sentinel = "PrivacyProbe-" + uuid4().hex
|
||||
with httpx.Client(
|
||||
base_url=BASE, timeout=15, trust_env=False
|
||||
) as client:
|
||||
user, _, session = actor(client)
|
||||
headers = auth(session)
|
||||
chat = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers,
|
||||
json={
|
||||
"title": "Synthetic telemetry",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
).json()["id"]
|
||||
message = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**headers, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": sentinel},
|
||||
)
|
||||
assert message.status_code == 201
|
||||
cases = []
|
||||
for retry in [False, True]:
|
||||
if retry:
|
||||
compose("stop", "--timeout", "1", "worker")
|
||||
trace_id = uuid4().hex
|
||||
trace_header = (
|
||||
"00-" + trace_id + "-" + uuid4().hex[:16] + "-01"
|
||||
)
|
||||
accepted = client.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
params={"filename": sentinel + ".png"},
|
||||
headers={
|
||||
**headers,
|
||||
"Content-Type": "image/png",
|
||||
"traceparent": trace_header,
|
||||
},
|
||||
content=raw,
|
||||
)
|
||||
assert (
|
||||
accepted.status_code == 202
|
||||
and accepted.json()["status"] == "queued"
|
||||
)
|
||||
attachment = accepted.json()["id"]
|
||||
job = sql(
|
||||
f"SELECT id FROM jobs WHERE attachment_id='{attachment}'::uuid"
|
||||
)
|
||||
if retry:
|
||||
sql(
|
||||
f"INSERT INTO pipeline_faults(target,phase,action,remaining) VALUES('{job}'::uuid,'before_effect','transient',1)"
|
||||
)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "worker")
|
||||
|
||||
def finished(identity=attachment):
|
||||
response = client.get(
|
||||
f"/api/v1/attachments/{identity}", headers=headers
|
||||
)
|
||||
return (
|
||||
response.status_code == 200
|
||||
and response.json()["status"] == "ready"
|
||||
)
|
||||
|
||||
wait(finished, timeout=90)
|
||||
original = client.get(
|
||||
f"/api/v1/attachments/{attachment}/content",
|
||||
headers=headers,
|
||||
)
|
||||
assert original.content == raw
|
||||
|
||||
def traced(identity=trace_id, retry_expected=retry):
|
||||
items = spans(identity)
|
||||
if len(
|
||||
[s for s in items if s["name"] == "attachment.process"]
|
||||
) < (2 if retry_expected else 1):
|
||||
return None
|
||||
if any(s["kind"] == "SPAN_KIND_CONSUMER" for s in items):
|
||||
# Independent export batches may arrive in a different
|
||||
# order. Require the whole chain before accepting it.
|
||||
try:
|
||||
return verify_chain(
|
||||
items, identity, retry=retry_expected
|
||||
)
|
||||
except (AssertionError, KeyError):
|
||||
return None
|
||||
|
||||
items = wait(traced, timeout=90)
|
||||
|
||||
def correlated(identity=trace_id):
|
||||
result = logs(identity)
|
||||
streams = result.get("data", {}).get("result", [])
|
||||
services = {
|
||||
x["stream"].get("service_name") for x in streams
|
||||
}
|
||||
return (
|
||||
result
|
||||
if {"messenger-api", "messenger-worker"} <= services
|
||||
else None
|
||||
)
|
||||
|
||||
correlated_logs = wait(correlated, timeout=90)
|
||||
span_ids = {s["span_id"] for s in items}
|
||||
streams = correlated_logs["data"]["result"]
|
||||
assert all(
|
||||
row["stream"].get("span_id") in span_ids for row in streams
|
||||
)
|
||||
assert any(
|
||||
row["stream"].get("request_id")
|
||||
== accepted.headers["X-Request-Id"]
|
||||
for row in streams
|
||||
)
|
||||
exported = json.dumps(
|
||||
{"spans": items, "logs": correlated_logs}
|
||||
)
|
||||
assert (
|
||||
sentinel not in exported
|
||||
and session["token"] not in exported
|
||||
)
|
||||
cases.append(
|
||||
{
|
||||
"retry": retry,
|
||||
"attachment_id": attachment,
|
||||
"job_id": job,
|
||||
"trace_id": trace_id,
|
||||
"request_id": accepted.headers["X-Request-Id"],
|
||||
"original_sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"attempt": int(
|
||||
sql(
|
||||
f"SELECT attempt FROM jobs WHERE id='{job}'::uuid"
|
||||
)
|
||||
),
|
||||
"spans": items,
|
||||
"correlated_logs": correlated_logs,
|
||||
}
|
||||
)
|
||||
report["causal_uploads"] = cases
|
||||
assert cases[1]["attempt"] >= 2
|
||||
report["privacy_sentinels_absent_from_traces_and_logs"] = True
|
||||
names = wait(
|
||||
lambda: fetch("prometheus", "/api/v1/label/__name__/values")[
|
||||
"data"
|
||||
]
|
||||
)
|
||||
required = {
|
||||
"messenger_http_requests_total",
|
||||
"messenger_http_duration_seconds_bucket",
|
||||
"messenger_job_attempts_total",
|
||||
"messenger_job_duration_seconds_bucket",
|
||||
"messenger_time_to_ready_seconds_bucket",
|
||||
"messenger_queue_depth",
|
||||
"messenger_oldest_job_age_seconds",
|
||||
"messenger_db_pool_used",
|
||||
"messenger_db_pool_waiting",
|
||||
"messenger_worker_busy",
|
||||
"messenger_worker_capacity",
|
||||
"messenger_process_cpu_seconds_total",
|
||||
"messenger_process_memory_bytes",
|
||||
"messenger_slo_decisions_total",
|
||||
}
|
||||
wait(
|
||||
lambda: (
|
||||
required
|
||||
<= set(
|
||||
fetch("prometheus", "/api/v1/label/__name__/values")[
|
||||
"data"
|
||||
]
|
||||
)
|
||||
)
|
||||
)
|
||||
names = fetch("prometheus", "/api/v1/label/__name__/values")["data"]
|
||||
report["metric_names"] = [
|
||||
n for n in names if n.startswith("messenger_")
|
||||
]
|
||||
series = fetch(
|
||||
"prometheus",
|
||||
"/api/v1/series",
|
||||
params={"match[]": '{__name__=~"messenger_.*"}'},
|
||||
)["data"]
|
||||
forbidden = {
|
||||
"user_id",
|
||||
"chat_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"job_id",
|
||||
"request_id",
|
||||
"trace_id",
|
||||
"filename",
|
||||
}
|
||||
assert all(not forbidden.intersection(s) for s in series)
|
||||
assert all(sentinel not in json.dumps(s) for s in series)
|
||||
report["metric_series_count"] = len(series)
|
||||
report["metric_labels_low_cardinality"] = True
|
||||
url = "http://127.0.0.1:" + os.getenv("GRAFANA_PORT", "3006")
|
||||
password = (ROOT / "secrets/grafana_password").read_text().strip()
|
||||
with httpx.Client(
|
||||
base_url=url, auth=("admin", password), trust_env=False, timeout=15
|
||||
) as grafana:
|
||||
dashboard = grafana.get("/api/dashboards/uid/messenger-lab6")
|
||||
dashboard.raise_for_status()
|
||||
imported = dashboard.json()["dashboard"]
|
||||
assert len(imported["panels"]) == 18
|
||||
sources = grafana.get("/api/datasources").json()
|
||||
assert {s["uid"] for s in sources} == {
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
}
|
||||
checks = {}
|
||||
for uid in ["prometheus", "loki", "tempo"]:
|
||||
r = grafana.get(f"/api/datasources/uid/{uid}/health")
|
||||
r.raise_for_status()
|
||||
assert r.json()["status"] == "OK", uid
|
||||
checks[uid] = r.json()["status"]
|
||||
result = grafana.post(
|
||||
"/api/ds/query",
|
||||
json={
|
||||
"queries": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"uid": "prometheus",
|
||||
"type": "prometheus",
|
||||
},
|
||||
"expr": "sum(messenger_http_requests_total)",
|
||||
"instant": True,
|
||||
"format": "table",
|
||||
"intervalMs": 5000,
|
||||
"maxDataPoints": 10,
|
||||
}
|
||||
],
|
||||
"from": "now-5m",
|
||||
"to": "now",
|
||||
},
|
||||
)
|
||||
result.raise_for_status()
|
||||
assert result.json()["results"]["A"]["frames"]
|
||||
report["grafana"] = {
|
||||
"dashboard_uid": imported["uid"],
|
||||
"panels": len(imported["panels"]),
|
||||
"datasources_health": checks,
|
||||
"actual_query_frames": len(
|
||||
result.json()["results"]["A"]["frames"]
|
||||
),
|
||||
}
|
||||
report["quantiles"] = {
|
||||
str(q): query(
|
||||
f"histogram_quantile({q},sum by(le)(rate(messenger_http_duration_seconds_bucket[2m])))"
|
||||
)
|
||||
for q in [0.5, 0.95, 0.99]
|
||||
}
|
||||
assert all(report["quantiles"].values())
|
||||
report["complete"] = True
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "worker")
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: causal API/publish/consumer/child/DB/S3, retry, correlated logs, privacy and Grafana"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user