86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Sample Docker CPU/RAM and PostgreSQL activity during a scaling run."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def compose(*args: str) -> str:
|
|
return subprocess.check_output(
|
|
["docker", "compose", "--env-file", ".env", *args],
|
|
cwd=ROOT,
|
|
stderr=subprocess.DEVNULL,
|
|
text=True,
|
|
)
|
|
|
|
|
|
def pg_activity() -> dict:
|
|
query = (
|
|
"select count(*) filter (where datname = current_database()) as total,"
|
|
" count(*) filter (where datname = current_database() and state = 'active') as active,"
|
|
" count(*) filter (where datname = current_database() and wait_event_type = 'Lock') as waiting"
|
|
" from pg_stat_activity;"
|
|
)
|
|
raw = compose(
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"sh",
|
|
"-c",
|
|
f'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "{query}"',
|
|
).strip()
|
|
total, active, waiting = (int(part) for part in raw.split("|"))
|
|
return {"connections": total, "active": active, "waiting": waiting}
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--duration", type=float, default=20.0)
|
|
parser.add_argument("--interval", type=float, default=1.0)
|
|
parser.add_argument("--output", default="evidence/track1_metrics.json")
|
|
args = parser.parse_args()
|
|
|
|
samples = []
|
|
started = time.monotonic()
|
|
while time.monotonic() - started < args.duration:
|
|
raw = subprocess.check_output(
|
|
["docker", "stats", "--no-stream", "--format", "{{json .}}"],
|
|
text=True,
|
|
)
|
|
containers = []
|
|
for line in raw.splitlines():
|
|
item = json.loads(line)
|
|
if not item["Name"].startswith("mtusi-lab3-"):
|
|
continue
|
|
containers.append(
|
|
{
|
|
"name": item["Name"],
|
|
"cpu_percent": item["CPUPerc"],
|
|
"mem_usage": item["MemUsage"],
|
|
"mem_percent": item["MemPerc"],
|
|
}
|
|
)
|
|
samples.append(
|
|
{
|
|
"t": round(time.monotonic() - started, 2),
|
|
"containers": containers,
|
|
"postgres": pg_activity(),
|
|
}
|
|
)
|
|
time.sleep(args.interval)
|
|
|
|
output = Path(args.output)
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
output.write_text(json.dumps(samples, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {len(samples)} samples to {output}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|