ЛР 7 — БПИ2304 — Кирюпина — на 3
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
SashaKirupina
2026-11-28 00:31:13 +03:00
parent 20afc2c790
commit 7fb93b31ba
93 changed files with 8017 additions and 122 deletions
+10
View File
@@ -0,0 +1,10 @@
FROM golang:1.24.3-alpine AS build
RUN apk add --no-cache git || apk add --no-cache git || apk add --no-cache git
RUN git clone --depth 1 --branch RELEASE.2025-04-16T18-13-26Z https://github.com/minio/mc.git /src
WORKDIR /src
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build for attempt in 1 2 3 4 5; do CGO_ENABLED=0 go build -trimpath -o /mc . && exit 0; done; exit 1
FROM alpine:3.22.1
RUN apk add --no-cache ca-certificates curl
COPY --from=build /mc /usr/local/bin/mc
ENTRYPOINT ["mc"]
+11
View File
@@ -0,0 +1,11 @@
FROM golang:1.24.3-alpine AS build
RUN apk add --no-cache git || apk add --no-cache git || apk add --no-cache git
RUN git clone --depth 1 --branch RELEASE.2025-04-22T22-12-26Z https://github.com/minio/minio.git /src
WORKDIR /src
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
for attempt in 1 2 3 4 5; do CGO_ENABLED=0 go build -trimpath -o /minio . && exit 0; done; exit 1
FROM alpine:3.22.1
RUN apk add --no-cache ca-certificates curl
COPY --from=build /minio /usr/local/bin/minio
ENTRYPOINT ["minio"]
+3 -5
View File
@@ -1,7 +1,5 @@
# Инфраструктура студента
# Инфраструктура lab7
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
compose.yaml содержит полный локальный стенд. Операторский запуск scripts/up.py выполняет порядок bootstrap; одного compose up для первого init/unseal недостаточно. src/tls-proxy.js использует общий network namespace только с конкретным telemetry backend; upstream разрешён исключительно на 127.0.0.1.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Границы, порты и identities описаны в contracts/trust-matrix.md. certs/, secrets/, operator/ генерируются локально и не включаются в исходники. OpenBao/migration/S3-init — отдельные операторские этапы; root credentials не передаются приложению и worker.
+263
View File
@@ -0,0 +1,263 @@
{
"uid": "messenger-lab7",
"title": "Messenger — lab7",
"schemaVersion": 40,
"version": 1,
"editable": false,
"timezone": "browser",
"refresh": "5s",
"time": {
"from": "now-30m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API requests / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (method,route) (rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m]))",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 2,
"title": "API 5xx / all business requests",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m])),0.000001)",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"max": 1
},
"overrides": []
}
},
{
"id": 3,
"title": "API p95 duration, seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95,sum by (le) (rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[1m])))",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "Jobs by outcome / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 5,
"title": "Worker p95 duration, seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95,sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"title": "Jobs total by outcome",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (messenger_jobs_total)",
"legendFormat": "{{route}} {{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 7,
"title": "messenger-api logs (TraceID opens Tempo)",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 24,
"h": 9
},
"targets": [
{
"refId": "A",
"expr": "{service_name=\"messenger-api\"}",
"queryType": "range"
}
],
"options": {
"showTime": true,
"showLabels": false,
"wrapLogMessage": true
}
},
{
"id": 8,
"title": "messenger-worker logs (TraceID opens Tempo)",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 33,
"w": 24,
"h": 9
},
"targets": [
{
"refId": "A",
"expr": "{service_name=\"messenger-worker\"}",
"queryType": "range"
}
],
"options": {
"showTime": true,
"showLabels": false,
"wrapLogMessage": true
}
},
{
"id": 9,
"title": "API and worker traces",
"type": "table",
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"gridPos": {
"x": 0,
"y": 42,
"w": 24,
"h": 8
},
"targets": [
{
"refId": "A",
"queryType": "traceql",
"query": "{ resource.service.name =~ \"messenger-.*\" }",
"tableType": "traces",
"limit": 20
}
]
}
]
}
@@ -0,0 +1,8 @@
apiVersion: 1
providers:
- name: Messenger
folder: MTUSI
type: file
editable: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,3 @@
# Datasources are generated locally by scripts/setup.py into secrets/datasources.yaml.
# That file contains the Grafana client certificate/private key and is not committed.
# compose.yaml mounts only the generated file; no plaintext data source is used.
+26
View File
@@ -0,0 +1,26 @@
global
log stdout format raw local0
maxconn 128
ssl-default-bind-options ssl-min-ver TLSv1.2
ssl-default-server-options ssl-min-ver TLSv1.2
defaults
mode http
timeout connect 3s
timeout client 30s
timeout server 30s
frontend ingress
bind :8443 ssl crt /tls/server.pem
http-request set-header X-Forwarded-For %[src]
default_backend api
backend api
balance roundrobin
option httpchk GET /health/ready
server api1 api1:8443 ssl verify required ca-file /tls/ca.crt crt /tls/client.pem verifyhost api1 sni str(api1) check inter 1s fall 2 rise 1 resolvers docker init-addr libc,none resolve-prefer ipv4
server api2 api2:8443 ssl verify required ca-file /tls/ca.crt crt /tls/client.pem verifyhost api2 sni str(api2) check inter 1s fall 2 rise 1 resolvers docker init-addr libc,none resolve-prefer ipv4
resolvers docker
nameserver docker 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 10s
+4 -4
View File
@@ -1,7 +1,7 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao lab7
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Конфигурация server-mode и file storage: config.hcl. Scoped политики: api.hcl, worker.hcl. Cert auth и KV настраиваются host-скриптом scripts/bao.py; служебные tokens TTL=300/max=600, после чтения отзываются. Полный bootstrap: scripts/up.py. После рестарта Bao требуется операторский unseal.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
operator/bao-init.json содержит root token и один unseal share, operator/ca.key — private CA. Они не монтируются в сервисы, не коммитятся и не включаются в архив. Для учебного 1-of-1 режима ответственность за защищённое хранение и backup лежит на операторе. Обычный рестарт API не требует unseal заново, если Bao уже открыт.
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
Каждый API/worker имеет только собственный leaf key/cert и публичный CA. Рабочие secrets читаются из OpenBao в память процесса. При sealed/unavailable Bao новый процесс не стартует; уже запущенный продолжает использовать статические KV credentials. Ротация и отзыв существующих DB-соединений не заявлены на оценку 3.
+2
View File
@@ -0,0 +1,2 @@
path "secret/data/api" { capabilities = ["read"] }
path "auth/token/revoke-self" { capabilities = ["update"] }
+11
View File
@@ -0,0 +1,11 @@
ui = true
disable_mlock = true
storage "file" { path = "/openbao/file" }
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/tls/cert.crt"
tls_key_file = "/tls/key.pem"
tls_client_ca_file = "/tls/ca.crt"
tls_min_version = "tls12"
}
api_addr = "https://bao:8200"
+2
View File
@@ -0,0 +1,2 @@
path "secret/data/worker" { capabilities = ["read"] }
path "auth/token/revoke-self" { capabilities = ["update"] }
+6 -4
View File
@@ -1,7 +1,9 @@
# Конфигурация наблюдаемости — реализовать
# Наблюдаемость lab7
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Сигналы lab6 сохранены: messenger_http_requests_total (method/route/status_class), messenger_http_duration_seconds histogram; messenger_jobs_total и messenger_job_duration_seconds histogram (job_type/outcome). Длительности в секундах, HTTP route — шаблон. Worker outcomes считают попытки, в том числе retry, а не только уникальные файлы. JSON logs содержат timestamp/severity/service.name/event и trace_id/span_id при активном span. SERVER/CONSUMER spans реальные; поля body/password/Authorization не экспортируются.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
API/worker отправляют OTLP по HTTPS/mTLS в otel-collector:3443. Collector экспортирует в loki:3443/otlp и tempo:3443, Prometheus снимает metrics с otel-collector:3443/metrics. Grafana обращается к каждому backend по HTTPS/mTLS. Роли и закрытые loopback hops: contracts/trust-matrix.md. Приватный datasource provisioning генерируется setup.py в secrets/, dashboard JSON остаётся в Git.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Prometheus хранит метрики, Loki — логи, Tempo — трассы. История в volumes, retention 3 дня. Dashboard messenger-lab7 показывает RPS, долю 5xx среди бизнес-запросов без health, p95 из histogram buckets, jobs, логи и traces. Примеры связанных trace_id/request_id/attachment_id — evidence/telemetry.json. Для Loki Explore: {service_name="messenger-api"} |= "REQUEST_ID"; для worker — messenger-worker и attachment_id. Из лога доступен View trace.
Очереди SDK logs/spans по 512, batch 128; Collector memory limiter 128 MiB + spike 32 MiB, Docker limit 256 MiB, exporter queue 256, retry до 10 секунд. Долгая недоступность telemetry backend может привести к потере наблюдений; readiness API зависит от DB/S3/broker, а не от Grafana. SLO/alerts уровня 4 не заявлены.
+59
View File
@@ -0,0 +1,59 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 127.0.0.1:9464
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: https://loki:3443/otlp
tls:
ca_file: /tls/ca.crt
cert_file: /tls/cert.crt
key_file: /tls/key.pem
timeout: 2s
sending_queue:
queue_size: 256
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
otlphttp/tempo:
endpoint: https://tempo:3443
tls:
ca_file: /tls/ca.crt
cert_file: /tls/cert.crt
key_file: /tls/key.pem
timeout: 2s
sending_queue:
queue_size: 256
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
service:
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
+42
View File
@@ -0,0 +1,42 @@
auth_enabled: false
server:
http_listen_port: 3100
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
common:
path_prefix: /loki
replication_factor: 1
ring:
instance_addr: 127.0.0.1
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
ingester:
wal:
enabled: true
dir: /loki/wal
frontend:
address: 127.0.0.1
+11
View File
@@ -0,0 +1,11 @@
global:
scrape_interval: 5s
scrape_configs:
- job_name: messenger
scheme: https
tls_config:
ca_file: /tls/ca.crt
cert_file: /tls/cert.crt
key_file: /tls/key.pem
static_configs:
- targets: [otel-collector:3443]
+24
View File
@@ -0,0 +1,24 @@
server:
http_listen_port: 3200
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+1
View File
@@ -0,0 +1 @@
[].