Lab7: HTTPS, mTLS, OpenBao, трек 2 PKI на оценку 5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=str(ROOT),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def http(method, path, body=None, headers=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers=headers or {})
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
raw = resp.read()
|
||||
payload = json.loads(raw.decode()) if raw else None
|
||||
return resp.status, dict(resp.headers), payload
|
||||
|
||||
|
||||
def main():
|
||||
stamp = uuid.uuid4().hex[:10]
|
||||
users = []
|
||||
for idx in range(2):
|
||||
username = f"tr_{stamp}_{idx}"
|
||||
http("POST", "/api/v1/users", {"username": username, "display_name": username, "password": "Password123!"})
|
||||
auth = "Basic " + base64.b64encode(f"{username}:Password123!".encode()).decode()
|
||||
_status, _headers, session = http("POST", "/api/v1/auth/sessions", headers={"Authorization": auth})
|
||||
users.append(session)
|
||||
_status, _headers, chat = http(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "t", "member_ids": [users[0]["user"]["id"], users[1]["user"]["id"]]},
|
||||
headers={"Authorization": "Bearer " + users[0]["token"]},
|
||||
)
|
||||
png = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
req = urllib.request.Request(
|
||||
BASE + f"/api/v1/chats/{chat['id']}/attachments?filename=t.png",
|
||||
data=png,
|
||||
method="POST",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"], "Content-Type": "image/png"},
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
attachment = json.loads(resp.read().decode())
|
||||
request_id = resp.headers.get("X-Request-Id")
|
||||
print("upload", resp.status, attachment["id"], request_id)
|
||||
for _ in range(60):
|
||||
_status, _headers, payload = http(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"]},
|
||||
)
|
||||
if payload.get("status") == "ready":
|
||||
print("ready")
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(6)
|
||||
for service in ("messenger-api", "messenger-worker"):
|
||||
q = urllib.parse.urlencode({"tags": f"service.name={service}", "limit": "20"})
|
||||
out = compose("exec", "-T", "tempo", "wget", "-qO-", f"http://127.0.0.1:3200/api/search?{q}")
|
||||
print(service, out.stdout[:800])
|
||||
q = urllib.parse.urlencode({"query": '{service_name="messenger-api"} |= "http_request"', "limit": "5"})
|
||||
out = compose("exec", "-T", "loki", "wget", "-qO-", "http://127.0.0.1:3100/loki/api/v1/query?" + q)
|
||||
print("loki", out.stdout[:600])
|
||||
# worker stop age probe
|
||||
compose("stop", "worker")
|
||||
req = urllib.request.Request(
|
||||
BASE + f"/api/v1/chats/{chat['id']}/attachments?filename=lag.png",
|
||||
data=png,
|
||||
method="POST",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"], "Content-Type": "image/png"},
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
queued = json.loads(resp.read().decode())
|
||||
print("queued", resp.status, queued["id"])
|
||||
ages = []
|
||||
fired = None
|
||||
started = time.time()
|
||||
while time.time() - started < 150:
|
||||
q = urllib.parse.urlencode(
|
||||
{
|
||||
"query": 'max(messenger_queue_oldest_job_age_seconds{messaging_destination_name="attachments.process"})'
|
||||
}
|
||||
)
|
||||
out = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/query?" + q)
|
||||
age = None
|
||||
try:
|
||||
payload = json.loads(out.stdout)
|
||||
rows = payload.get("data", {}).get("result", [])
|
||||
if rows:
|
||||
age = float(rows[0]["value"][1])
|
||||
except Exception:
|
||||
age = None
|
||||
ages.append({"t": round(time.time() - started, 1), "age": age})
|
||||
alerts = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/alerts")
|
||||
try:
|
||||
alert_payload = json.loads(alerts.stdout)
|
||||
for item in alert_payload.get("data", {}).get("alerts", []):
|
||||
if item.get("labels", {}).get("alertname") == "GrowingQueueLag" and item.get("state") == "firing":
|
||||
fired = round(time.time() - started, 1)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if fired is not None:
|
||||
break
|
||||
time.sleep(5)
|
||||
compose("start", "worker")
|
||||
print(json.dumps({"ages": ages[-8:], "fired_after_seconds": fired}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user