Реализовать лабораторную работу 3
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
from compose_helpers import ROOT, compose
|
||||
|
||||
|
||||
def docker(*args, input=None, timeout=90):
|
||||
return subprocess.run(["docker", *args], input=input, text=True, capture_output=True,
|
||||
check=True, timeout=timeout).stdout.strip()
|
||||
|
||||
|
||||
def api_ids():
|
||||
return compose("ps", "-q", "api").splitlines()
|
||||
|
||||
|
||||
def inspect(container):
|
||||
return json.loads(docker("inspect", container))[0]
|
||||
|
||||
|
||||
def alias(container):
|
||||
headers = docker("exec", container, "curl", "-fsS", "-D", "-", "-o", "/dev/null",
|
||||
"http://127.0.0.1:8080/health/live")
|
||||
return next(line.split(":", 1)[1].strip() for line in headers.splitlines()
|
||||
if line.lower().startswith("x-instance-id:"))
|
||||
|
||||
|
||||
def runtime(command):
|
||||
lb = compose("ps", "-q", "lb")
|
||||
return docker("exec", "-i", lb, "nc", "-w", "2", "127.0.0.1", "9999",
|
||||
input=command + "\n", timeout=5)
|
||||
|
||||
|
||||
def stats():
|
||||
return list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
|
||||
|
||||
|
||||
def servers():
|
||||
return [row for row in stats() if row["pxname"] == "messenger" and row["svname"].startswith("api")]
|
||||
|
||||
|
||||
def wait_api(base_url, expected, timeout=45):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
rows = servers()
|
||||
up = [row for row in rows if row["status"] == "UP"]
|
||||
if len(up) == expected:
|
||||
with urlopen(base_url + "/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (OSError, subprocess.SubprocessError, StopIteration):
|
||||
pass
|
||||
time.sleep(.25)
|
||||
raise RuntimeError("API replicas did not become ready")
|
||||
|
||||
|
||||
def recreate(replicas=2, cpus=1, memory="384m", pool=20, batching=True, database_cpus=.5):
|
||||
import os
|
||||
environment = dict(os.environ, API_REPLICAS=str(replicas), API_CPUS=str(cpus),
|
||||
API_MEMORY=memory, DB_POOL_SIZE=str(pool), MESSAGE_BATCHING=str(batching).lower(),
|
||||
POSTGRES_CPUS=str(database_cpus))
|
||||
subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps",
|
||||
"--scale", "api=" + str(replicas), "--force-recreate", "api"],
|
||||
cwd=ROOT, env=environment, capture_output=True, text=True, check=True, timeout=90)
|
||||
|
||||
|
||||
def counters():
|
||||
result = {}
|
||||
for service in ("api", "postgres", "lb", "redis"):
|
||||
for container in compose("ps", "-q", service).splitlines():
|
||||
info = inspect(container)
|
||||
data = docker("exec", container, "cat", "/sys/fs/cgroup/cpu.stat",
|
||||
"/sys/fs/cgroup/memory.current").splitlines()
|
||||
values = dict(line.split() for line in data[:-1])
|
||||
result[container] = {
|
||||
"service": service, "name": info["Name"].lstrip("/"),
|
||||
"cpu_seconds": int(values["usage_usec"]) / 1e6,
|
||||
"throttled_seconds": int(values["throttled_usec"]) / 1e6,
|
||||
"throttled_periods": int(values["nr_throttled"]),
|
||||
"memory_bytes": int(data[-1]),
|
||||
"cpu_limit": info["HostConfig"]["NanoCpus"] / 1e9,
|
||||
"memory_limit": info["HostConfig"]["Memory"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def counter_delta(before, after, seconds):
|
||||
result = []
|
||||
for container, current in after.items():
|
||||
old = before.get(container, current)
|
||||
row = {key: current[key] for key in ("service", "name", "cpu_limit", "memory_limit", "memory_bytes")}
|
||||
row["used_cpu_cores"] = round((current["cpu_seconds"] - old["cpu_seconds"]) / seconds, 3)
|
||||
row["throttled_seconds"] = round(current["throttled_seconds"] - old["throttled_seconds"], 3)
|
||||
row["throttled_periods"] = current["throttled_periods"] - old["throttled_periods"]
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
|
||||
def rolling_replace(base_url="http://127.0.0.1:18080", build=True):
|
||||
originals = api_ids()
|
||||
if len(originals) < 2:
|
||||
raise RuntimeError("Rolling replacement requires at least two API replicas")
|
||||
if build:
|
||||
compose("build", "--build-arg", "BUILD_REVISION=rolling-" + str(time.time_ns()), "api", timeout=180)
|
||||
records = []
|
||||
for old in originals:
|
||||
before = set(api_ids())
|
||||
old_info = inspect(old)
|
||||
old_alias = alias(old)
|
||||
old_ip = next(iter(old_info["NetworkSettings"]["Networks"].values()))["IPAddress"]
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", "api=" + str(len(originals) + 1), "api")
|
||||
wait_api(base_url, len(originals) + 1)
|
||||
added = (set(api_ids()) - before).pop()
|
||||
slot = next(row["svname"] for row in servers() if row.get("addr", "").split(":")[0] == old_ip)
|
||||
runtime("set server messenger/" + slot + " state drain")
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
active = next(row for row in servers() if row["svname"] == slot)
|
||||
if int(active["scur"]) == 0:
|
||||
break
|
||||
time.sleep(.1)
|
||||
else:
|
||||
raise RuntimeError("Backend did not drain")
|
||||
docker("stop", "--time", "8", old)
|
||||
docker("rm", old)
|
||||
runtime("set server messenger/" + slot + " state ready")
|
||||
wait_api(base_url, len(originals))
|
||||
records.append({"old_container": old, "old_instance": old_alias,
|
||||
"old_image": old_info["Image"], "new_container": added,
|
||||
"new_instance": alias(added), "new_image": inspect(added)["Image"]})
|
||||
return records
|
||||
Reference in New Issue
Block a user