ЛР6: наблюдаемость, SLO и диагностика отказов
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
New-Item -ItemType Directory -Force secrets | Out-Null
|
||||
$values = @{postgres_db='messenger'; postgres_user='messenger'; postgres_password=''; minio_root_user='labadmin'; minio_root_password=''; s3_access_key_id='labapi'; s3_secret_access_key=''; grafana_admin_password=''}
|
||||
foreach ($name in $values.Keys) {
|
||||
$path = Join-Path secrets ($name + '.txt')
|
||||
if (!(Test-Path -LiteralPath $path)) {
|
||||
$value = $values[$name]
|
||||
if (!$value) { $value = [Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) }
|
||||
[System.IO.File]::WriteAllText((Join-Path (Get-Location) $path), $value)
|
||||
}
|
||||
}
|
||||
if (!(Test-Path .env)) { Copy-Item .env.example .env }
|
||||
@@ -0,0 +1,117 @@
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ["docker", "compose", "-f", "docker-compose.yml", "-f", "compose.local.yaml"]
|
||||
|
||||
|
||||
def cmd(*args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, encoding="utf-8").strip()
|
||||
|
||||
|
||||
def save(name, value):
|
||||
(ROOT / "evidence" / name).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def containers():
|
||||
ids = cmd(*COMPOSE, "ps", "-q").splitlines()
|
||||
data = json.loads(cmd("docker", "inspect", *ids))
|
||||
return [
|
||||
{
|
||||
"service": row["Config"]["Labels"]["com.docker.compose.service"],
|
||||
"image": row["Config"]["Image"],
|
||||
"image_id": row["Image"],
|
||||
"started_at": row["State"]["StartedAt"],
|
||||
"health": row["State"].get("Health", {}).get("Status", row["State"]["Status"]),
|
||||
"memory_limit_bytes": row["HostConfig"]["Memory"],
|
||||
"nano_cpus": row["HostConfig"]["NanoCpus"],
|
||||
"volumes": [item["Name"] for item in row["Mounts"] if item["Type"] == "volume"],
|
||||
}
|
||||
for row in data
|
||||
]
|
||||
|
||||
|
||||
def verify_sources():
|
||||
protected = ["README.md", "COURSE.md", "contracts", "tests", "lab.json"]
|
||||
subprocess.run(
|
||||
["git", "diff", "--exit-code", "470d9d6", "--", *protected], cwd=ROOT, check=True
|
||||
)
|
||||
names = cmd(
|
||||
"git", "-c", "core.quotePath=false", "ls-files", "-c", "-o", "--exclude-standard"
|
||||
).splitlines()
|
||||
root_secrets = ROOT / "secrets"
|
||||
credentials = [
|
||||
path.read_bytes().strip()
|
||||
for path in root_secrets.glob("*.txt")
|
||||
if "password" in path.stem or "secret_access_key" in path.stem
|
||||
]
|
||||
assert all(len(value) > 12 for value in credentials), "expected generated secrets"
|
||||
source = {}
|
||||
for name in names:
|
||||
if not (ROOT / name).is_file():
|
||||
continue
|
||||
content = (ROOT / name).read_bytes()
|
||||
assert not any(
|
||||
secret in content for secret in credentials
|
||||
), "generated credential in Git-visible file"
|
||||
if name.startswith(
|
||||
("src/", "worker/", "infra/otel/", "student-tests/", "scripts/")
|
||||
) or name in (
|
||||
"docker-compose.yml",
|
||||
"Dockerfile",
|
||||
"compose.test.yaml",
|
||||
"compose.local.yaml",
|
||||
"build.gradle",
|
||||
):
|
||||
source[name] = hashlib.sha256(content).hexdigest()
|
||||
save("source-sha256.json", source)
|
||||
print("PASS public starter/contract intact, generated secrets absent from Git-visible files")
|
||||
|
||||
|
||||
def main():
|
||||
service_state = containers()
|
||||
assert (
|
||||
len(
|
||||
[row for row in service_state if row["service"] == "api" and row["health"] == "healthy"]
|
||||
)
|
||||
== 2
|
||||
)
|
||||
assert len([row for row in service_state if row["service"] == "worker"]) == 2
|
||||
save(
|
||||
"environment.json",
|
||||
{
|
||||
"timestamp": datetime.now().astimezone().isoformat(),
|
||||
"skeleton": "470d9d6",
|
||||
"transfer_source": "ef7e8c3",
|
||||
"engine": cmd(
|
||||
"docker",
|
||||
"info",
|
||||
"--format",
|
||||
"version={{.ServerVersion}} cpus={{.NCPU}} memory_bytes={{.MemTotal}}",
|
||||
),
|
||||
"services": service_state,
|
||||
},
|
||||
)
|
||||
save(
|
||||
"resources.json",
|
||||
[
|
||||
json.loads(line)
|
||||
for line in cmd(
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--format",
|
||||
"{{json .}}",
|
||||
*cmd(*COMPOSE, "ps", "-q").splitlines(),
|
||||
).splitlines()
|
||||
],
|
||||
)
|
||||
verify_sources()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
@@ -0,0 +1,9 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ids = docker compose ps -q
|
||||
$before = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids
|
||||
$before | Set-Content evidence/restart-before.txt
|
||||
docker compose restart db redis minio broker api worker dispatcher lb otel-collector prometheus loki tempo grafana
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
$ids = docker compose ps -q
|
||||
$after = docker inspect --format '{{.Name}} {{.State.StartedAt}}' $ids
|
||||
$after | Set-Content evidence/restart-after.txt
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
docker compose restart db redis minio broker api worker dispatcher lb otel-collector prometheus loki tempo grafana
|
||||
@@ -0,0 +1,47 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path $PSScriptRoot -Parent)
|
||||
$env:BASE_URL = 'http://127.0.0.1:18085'
|
||||
$env:PYTHONPATH = (Resolve-Path tests).Path
|
||||
$base = @('compose', '-f', 'docker-compose.yml', '-f', 'compose.local.yaml')
|
||||
$proof = $base + @('-f', 'compose.test.yaml')
|
||||
|
||||
function Invoke-Checked {
|
||||
param([string]$Name, [string]$Command, [string[]]$Arguments)
|
||||
& $Command @Arguments *> "evidence/$Name.txt"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Get-Content "evidence/$Name.txt" -Tail 25
|
||||
throw "$Name failed ($LASTEXITCODE)"
|
||||
}
|
||||
Write-Host "PASS $Name"
|
||||
}
|
||||
|
||||
function Wait-Api {
|
||||
py -c "import sys; sys.path.insert(0,'student-tests'); from pipeline_support import ready_api; ready_api()"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API readiness not confirmed' }
|
||||
}
|
||||
|
||||
try {
|
||||
Invoke-Checked 'contract-check' 'py' @('scripts/check_contract.py')
|
||||
Invoke-Checked 'openapi-validation' 'py' @('scripts/validate_openapi.py')
|
||||
Invoke-Checked 'style' 'py' @('scripts/style.py')
|
||||
Invoke-Checked 'java-build' '.\gradlew.bat' @('test', '--no-daemon')
|
||||
Invoke-Checked 'stack-test-profile' 'docker' ($proof + @('up', '-d', '--build'))
|
||||
Wait-Api
|
||||
Invoke-Checked 'smoke' 'py' @('tests/smoke.py')
|
||||
Invoke-Checked 'observe' 'py' @('student-tests/observe.py')
|
||||
foreach ($name in @('core','faults','retention','boundaries','ack_guard','filename','upload_crash','history_capacity')) {
|
||||
Invoke-Checked "pipeline-$name" 'py' @("student-tests/pipeline_$name.py")
|
||||
}
|
||||
Invoke-Checked 'stack-ordinary' 'docker' ($base + @('up', '-d'))
|
||||
Wait-Api
|
||||
Invoke-Checked 'incidents' 'py' @('student-tests/incidents.py')
|
||||
Invoke-Checked 'load' 'py' @('tests/load.py', '--duration', '30', '--concurrency', '4', '--output', 'evidence/load.json')
|
||||
Invoke-Checked 'persistence' 'py' @('tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.cmd')
|
||||
Wait-Api
|
||||
Invoke-Checked 'failover' 'py' @('tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one.cmd')
|
||||
Invoke-Checked 'stack-final' 'docker' ($base + @('up', '-d', 'api'))
|
||||
Wait-Api
|
||||
Invoke-Checked 'environment' 'py' @('scripts/capture_evidence.py')
|
||||
} finally {
|
||||
docker @base up -d
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1"
|
||||
@@ -0,0 +1,13 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$replicas = docker compose ps -q api
|
||||
foreach ($replica in $replicas) {
|
||||
$alias = docker inspect --format '{{.Config.Hostname}}' $replica
|
||||
if ($alias -eq $env:TARGET_INSTANCE_ID) {
|
||||
docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-before.txt
|
||||
docker stop --time 2 $replica
|
||||
$result = $LASTEXITCODE
|
||||
docker inspect --format "{{.Name}} {{.Config.Hostname}} {{.State.Status}}" $replica | Set-Content evidence/stop-one-after.txt
|
||||
exit $result
|
||||
}
|
||||
}
|
||||
exit 1
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
for id in $(docker compose ps -q api); do
|
||||
if [ "$(docker inspect --format '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop -t 2 "$id"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
@@ -0,0 +1,87 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VERSION = "1.28.0"
|
||||
SHA256 = "32342e7c1b4600f80df3471da46aee8012d3e1445d5ea1be1fb71289b07cc735"
|
||||
|
||||
|
||||
def formatter():
|
||||
jar = Path(tempfile.gettempdir()) / f"google-java-format-{VERSION}-all-deps.jar"
|
||||
if not jar.exists():
|
||||
url = (
|
||||
"https://repo.maven.apache.org/maven2/com/google/googlejavaformat/"
|
||||
f"google-java-format/{VERSION}/{jar.name}"
|
||||
)
|
||||
with urllib.request.urlopen(url, timeout=60) as response:
|
||||
jar.write_bytes(response.read())
|
||||
if hashlib.sha256(jar.read_bytes()).hexdigest() != SHA256:
|
||||
raise RuntimeError("Java formatter checksum mismatch")
|
||||
return jar
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
args = parser.parse_args()
|
||||
java_home = os.environ.get("JAVA_HOME")
|
||||
java = str(Path(java_home) / "bin" / "java") if java_home else "java"
|
||||
files = sorted(str(p.relative_to(ROOT)) for p in (ROOT / "src").rglob("*.java"))
|
||||
mode = ["--replace"] if args.apply else ["--dry-run", "--set-exit-if-changed"]
|
||||
subprocess.run([java, "-jar", str(formatter()), "--aosp", *mode, *files], cwd=ROOT, check=True)
|
||||
python = [
|
||||
"worker/pipeline",
|
||||
"scripts/style.py",
|
||||
"scripts/capture_evidence.py",
|
||||
]
|
||||
python += sorted(str(p.relative_to(ROOT)) for p in (ROOT / "student-tests").glob("*.py"))
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "black", *([] if args.apply else ["--check"]), *python],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
check_controllers()
|
||||
print("PASS Java AOSP / Python Black style")
|
||||
|
||||
|
||||
def check_controllers():
|
||||
directory = ROOT / "src/main/java/ru/mtusi/messenger/controller"
|
||||
operations = 0
|
||||
for path in directory.glob("*Controller.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
fields = re.findall(r"private final (\w+Service) (\w+);", source)
|
||||
if "@RequiredArgsConstructor" not in source or len(fields) != 1:
|
||||
raise AssertionError(f"Controller DI contract: {path.name}")
|
||||
bodies = re.findall(r"@Override\s+public [^{}]+\{([^{}]*)\}", source)
|
||||
if not bodies:
|
||||
raise AssertionError(f"Controller has no operations: {path.name}")
|
||||
service = fields[0][1]
|
||||
for body in bodies:
|
||||
if body.count(";") != 1 or len(re.findall(rf"\b{service}\.\w+\(", body)) != 1:
|
||||
raise AssertionError(f"Controller must call one service: {path.name}")
|
||||
if not re.fullmatch(rf"\s*(?:return )?{service}\.\w+\([^;]*\);\s*", body):
|
||||
raise AssertionError(f"Controller contains extra logic: {path.name}")
|
||||
operations += len(bodies)
|
||||
for path in directory.glob("*Api.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
if source.count("/**") != source.count("@Operation(") + 1:
|
||||
raise AssertionError(f"Missing API documentation: {path.name}")
|
||||
for path in (ROOT / "src/main/java").rglob("*.java"):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
if "@Autowired" in source:
|
||||
raise AssertionError(f"Use constructor injection: {path.name}")
|
||||
if re.search(r"^import .*\*;", source, re.MULTILINE):
|
||||
raise AssertionError(f"Use explicit imports: {path.name}")
|
||||
print(f"PASS {operations} controller operations: one service call, constructor DI, API Javadoc")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user