93 lines
4.1 KiB
Python
93 lines
4.1 KiB
Python
"""Container lifecycle check; run explicitly after building the image."""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
@unittest.skipUnless(
|
|
__name__ == "__main__" or os.environ.get("LAB1_DOCKER_LIFECYCLE") == "1",
|
|
"requires Docker; run this file directly",
|
|
)
|
|
class ContainerLifecycle(unittest.TestCase):
|
|
def test_memory_health_user_and_sigterm(self):
|
|
name = f"mtusi-lab1-lifecycle-{os.getpid()}"
|
|
image = os.environ.get("LAB1_IMAGE", "mtusi-messenger:lab1")
|
|
|
|
def docker(*args):
|
|
return subprocess.run(["docker", *args], check=True, capture_output=True, text=True).stdout.strip()
|
|
|
|
def request(base, method, path, body=None, user=None):
|
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
headers = {"Content-Type": "application/json"} if body is not None else {}
|
|
if user:
|
|
headers["X-User-Id"] = user
|
|
req = urllib.request.Request(base + path, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=2) as response:
|
|
return response.status, json.load(response)
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, json.load(error)
|
|
|
|
def ready(base):
|
|
deadline = time.monotonic() + 40
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if request(base, "GET", "/health/ready")[0] == 200:
|
|
return
|
|
except (OSError, TimeoutError):
|
|
pass
|
|
time.sleep(0.25)
|
|
self.fail("container did not become ready within 40 seconds")
|
|
|
|
docker("run", "-d", "--name", name, "-p", "127.0.0.1::8080", image)
|
|
try:
|
|
port = docker("port", name, "8080/tcp").rsplit(":", 1)[1]
|
|
base = f"http://127.0.0.1:{port}"
|
|
ready(base)
|
|
deadline = time.monotonic() + 20
|
|
while docker("inspect", "-f", "{{.State.Health.Status}}", name) != "healthy":
|
|
self.assertLess(time.monotonic(), deadline, "Docker healthcheck never became healthy")
|
|
time.sleep(0.5)
|
|
uid = docker("exec", name, "id", "-u")
|
|
self.assertNotEqual(uid, "0")
|
|
|
|
username = f"lifecycle_{os.getpid()}"
|
|
status, user = request(base, "POST", "/api/v1/users", {"username": username, "display_name": "Проверка"})
|
|
self.assertEqual(status, 201)
|
|
user_id = user["id"]
|
|
status, chat = request(base, "POST", "/api/v1/chats", {"title": "Жизненный цикл", "member_ids": [user_id]}, user_id)
|
|
self.assertEqual(status, 201)
|
|
marker = f"private-message-{os.getpid()}"
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
self.assertEqual(request(base, "POST", path, {"text": marker}, user_id)[0], 201)
|
|
status, history = request(base, "GET", path, user=user_id)
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual([item["text"] for item in history["items"]], [marker])
|
|
|
|
docker("restart", "--time", "10", name)
|
|
port = docker("port", name, "8080/tcp").rsplit(":", 1)[1]
|
|
base = f"http://127.0.0.1:{port}"
|
|
ready(base)
|
|
self.assertEqual(request(base, "GET", "/api/v1/users/me", user=user_id)[0], 401)
|
|
|
|
started = time.monotonic()
|
|
docker("stop", "--time", "10", name)
|
|
elapsed = time.monotonic() - started
|
|
self.assertLessEqual(elapsed, 10, f"SIGTERM shutdown took {elapsed:.2f}s")
|
|
self.assertEqual(docker("inspect", "-f", "{{.State.ExitCode}}", name), "0")
|
|
with self.assertRaises(urllib.error.URLError):
|
|
request(base, "GET", "/health/ready")
|
|
self.assertNotIn(marker, docker("logs", name))
|
|
print(f"lifecycle: healthy, uid={uid}, memory reset=401, SIGTERM={elapsed:.2f}s, closed port, no message text in stdout")
|
|
finally:
|
|
docker("rm", "-f", name)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|