chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065. Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public tests, README, REPORT and evidence of lab 6 are not carried over; infra and scripts of the lab 7 skeleton stay as they are. Makefile is the lab 6 one with the lab 7 skeleton part restored (HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore are taken from lab 6 because both skeletons have the same files; .env.example is the lab 6 one without changes. The compose project, image and CI prefix are renamed to lab7, and references to the previous lab now name lab6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""CPU и память контейнера по его cgroup v2 изнутри (design change
|
||||
`job-trace-propagation`, решение 12).
|
||||
|
||||
Без сокета Docker: доступ к API Docker равен root на ВМ. Файлы читает callback
|
||||
сбора метрик (микросекунды), корень cgroup — параметр, по умолчанию
|
||||
`CGROUP_ROOT`: быстрые тесты дают временный каталог. У worker cgroup включает
|
||||
процессы обработки. Значение `max` в `cpu.max` и `memory.max` — предела нет,
|
||||
точки нет.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from opentelemetry.metrics import Meter, Observation
|
||||
|
||||
from src.utils.constants import (
|
||||
METRIC_CONTAINER_CPU_LIMIT,
|
||||
METRIC_CONTAINER_CPU_TIME,
|
||||
METRIC_CONTAINER_MEMORY_LIMIT,
|
||||
METRIC_CONTAINER_MEMORY_USAGE,
|
||||
)
|
||||
|
||||
_USEC = 1_000_000
|
||||
_NO_LIMIT = "max"
|
||||
|
||||
|
||||
def _read(path: Path) -> str | None:
|
||||
try:
|
||||
return path.read_text().strip()
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def cpu_seconds(root: Path) -> float | None:
|
||||
"""`usage_usec` из `cpu.stat` в секундах."""
|
||||
text = _read(root / "cpu.stat")
|
||||
if text is None:
|
||||
return None
|
||||
for line in text.splitlines():
|
||||
name, _, value = line.partition(" ")
|
||||
if name == "usage_usec" and value.strip().isdigit():
|
||||
return int(value) / _USEC
|
||||
return None
|
||||
|
||||
|
||||
def memory_bytes(root: Path) -> int | None:
|
||||
text = _read(root / "memory.current")
|
||||
return int(text) if text is not None and text.isdigit() else None
|
||||
|
||||
|
||||
def cpu_limit(root: Path) -> float | None:
|
||||
"""Квота к периоду `cpu.max` в ядрах; `max` — предела нет."""
|
||||
text = _read(root / "cpu.max")
|
||||
if text is None:
|
||||
return None
|
||||
parts = text.split()
|
||||
if len(parts) != 2 or parts[0] == _NO_LIMIT:
|
||||
return None
|
||||
try:
|
||||
quota, period = int(parts[0]), int(parts[1])
|
||||
except ValueError:
|
||||
return None
|
||||
return quota / period if period > 0 else None
|
||||
|
||||
|
||||
def memory_limit(root: Path) -> int | None:
|
||||
text = _read(root / "memory.max")
|
||||
if text is None or text == _NO_LIMIT or not text.isdigit():
|
||||
return None
|
||||
return int(text)
|
||||
|
||||
|
||||
def available(root: Path) -> bool:
|
||||
"""Метрики контейнера есть, если читаются `cpu.stat` и
|
||||
`memory.current`."""
|
||||
return cpu_seconds(root) is not None and memory_bytes(root) is not None
|
||||
|
||||
|
||||
def _observe(value: Any) -> Iterable[Observation]:
|
||||
return [] if value is None else [Observation(value)]
|
||||
|
||||
|
||||
def register(meter: Meter, *, root: Path) -> None:
|
||||
"""Наблюдаемые инструменты контейнера; вызывающий проверил
|
||||
`available`."""
|
||||
meter.create_observable_counter(
|
||||
METRIC_CONTAINER_CPU_TIME,
|
||||
callbacks=[
|
||||
lambda _options: _observe(cpu_seconds(root)),
|
||||
],
|
||||
unit="s",
|
||||
description="CPU time of the container",
|
||||
)
|
||||
meter.create_observable_up_down_counter(
|
||||
METRIC_CONTAINER_MEMORY_USAGE,
|
||||
callbacks=[lambda _options: _observe(memory_bytes(root))],
|
||||
unit="By",
|
||||
description="Memory usage of the container",
|
||||
)
|
||||
meter.create_observable_up_down_counter(
|
||||
METRIC_CONTAINER_CPU_LIMIT,
|
||||
callbacks=[lambda _options: _observe(cpu_limit(root))],
|
||||
unit="{cpu}",
|
||||
description="CPU limit of the container",
|
||||
)
|
||||
meter.create_observable_up_down_counter(
|
||||
METRIC_CONTAINER_MEMORY_LIMIT,
|
||||
callbacks=[lambda _options: _observe(memory_limit(root))],
|
||||
unit="By",
|
||||
description="Memory limit of the container",
|
||||
)
|
||||
Reference in New Issue
Block a user