This commit is contained in:
2026-10-17 08:59:12 +03:00
parent 95aed3c25b
commit 7ffebe65d0
52 changed files with 1315 additions and 204 deletions
+15
View File
@@ -0,0 +1,15 @@
param(
[int]$DurationSeconds = 90,
[string]$Output = "evidence/lab3/pg-stat-activity.log"
)
$end = (Get-Date).AddSeconds($DurationSeconds)
"=== pg_stat_activity collection started at $(Get-Date -Format o) ===" | Out-File $Output
while ((Get-Date) -lt $end) {
"--- $(Get-Date -Format o) ---" | Add-Content $Output
docker compose exec -T db psql -U messenger -d messenger -c "SELECT state, wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE datname='messenger' GROUP BY 1,2,3 ORDER BY 4 DESC;" 2>&1 | Add-Content $Output
Start-Sleep -Seconds 5
}
"=== collection finished at $(Get-Date -Format o) ===" | Add-Content $Output
+21
View File
@@ -0,0 +1,21 @@
param(
[int]$DurationSeconds = 90,
[string]$Output = "evidence/lab3/docker-stats.csv"
)
$header = "timestamp,name,cpu_percent,mem_usage,mem_percent,net_io,block_io,pids"
Set-Content -Path $Output -Value $header
$end = (Get-Date).AddSeconds($DurationSeconds)
Write-Host "Collecting stats for $DurationSeconds seconds..."
while ((Get-Date) -lt $end) {
$timestamp = (Get-Date).ToString("o")
$stats = docker stats --no-stream --format "{{.Name}},{{.CPUPerc}},{{.MemUsage}},{{.MemPerc}},{{.NetIO}},{{.BlockIO}},{{.PIDs}}"
foreach ($line in $stats) {
Add-Content -Path $Output -Value "$timestamp,$line"
}
Start-Sleep -Seconds 2
}
Write-Host "Done. Rows: $((Get-Content $Output | Measure-Object -Line).Lines)"
+53
View File
@@ -0,0 +1,53 @@
import pandas as pd
import matplotlib.pyplot as plt
import os
# Создаем папку, если ее нет
os.makedirs('evidence/lab3/charts', exist_ok=True)
# Загружаем данные из CSV
csv_path = 'evidence/lab3/series-summary.csv'
if not os.path.exists(csv_path):
print(f"ОШИБКА: Файл {csv_path} не найден! Сначала создайте его.")
exit(1)
df = pd.read_csv(csv_path)
# --- ГРАФИК 1: RPS от числа реплик (Серия A) ---
df_a = df[df['series'] == 'A'].sort_values('replicas')
plt.figure(figsize=(8, 5))
plt.plot(df_a['replicas'], df_a['successful_rps'], marker='o', linestyle='-', color='red', linewidth=2, markersize=8)
plt.title('Series A: RPS vs Replicas (Fixed 2 CPU)', fontsize=14)
plt.xlabel('Number of Replicas', fontsize=12)
plt.ylabel('Successful RPS', fontsize=12)
plt.xticks(df_a['replicas'])
plt.grid(True, linestyle='--', alpha=0.7)
plt.savefig('evidence/lab3/charts/seriesA-rps-vs-replicas.png', bbox_inches='tight')
plt.close()
# --- ГРАФИК 2: RPS от суммарного CPU (Серия B) ---
df_b = df[df['series'] == 'B'].sort_values('total_cpu')
plt.figure(figsize=(8, 5))
plt.plot(df_b['total_cpu'], df_b['successful_rps'], marker='s', linestyle='-', color='blue', linewidth=2, markersize=8)
plt.title('Series B: RPS vs Total CPU (2 Replicas)', fontsize=14)
plt.xlabel('Total CPU Cores', fontsize=12)
plt.ylabel('Successful RPS', fontsize=12)
plt.xticks(df_b['total_cpu'])
plt.grid(True, linestyle='--', alpha=0.7)
plt.savefig('evidence/lab3/charts/seriesB-rps-vs-cpu.png', bbox_inches='tight')
plt.close()
# --- ГРАФИК 3: Сравнение p95 ---
plt.figure(figsize=(10, 5))
# Красим столбцы: серия А - красные, серия B - синие
colors = ['red' if s == 'A' else 'blue' for s in df['series']]
plt.bar(df['config'], df['p95_ms'], color=colors)
plt.title('p95 Latency by Configuration', fontsize=14)
plt.xlabel('Configuration', fontsize=12)
plt.ylabel('p95 Latency (ms)', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.savefig('evidence/lab3/charts/comparison-p95.png', bbox_inches='tight')
plt.close()
print("✅ Графики успешно созданы из series-summary.csv в evidence/lab3/charts/")
+52
View File
@@ -0,0 +1,52 @@
$ErrorActionPreference = 'Stop'
$logDir = "evidence\lab3"
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
# 1. Создаем тестового юзера (на случай чистого volume)
curl.exe -s -o NUL -X POST http://127.0.0.1:8080/api/v1/users -H "Content-Type: application/json" -d '{\"username\":\"lbtest\",\"display_name\":\"L\",\"password\":\"validpassword123\"}'
# 2. Получаем токен и создаем чат
$TOKEN = (curl.exe -s -X POST http://127.0.0.1:8080/api/v1/auth/sessions -u "lbtest:validpassword123" | ConvertFrom-Json).token
$USER_ID = (curl.exe -s http://127.0.0.1:8080/api/v1/users/me -H "Authorization: Bearer $TOKEN" | ConvertFrom-Json).id
$CHAT_ID = (curl.exe -s -X POST http://127.0.0.1:8080/api/v1/chats -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d ('{\"title\":\"lb-test\",\"member_ids\":[\"' + $USER_ID + '\"]}') | ConvertFrom-Json).id
$out = "$logDir\lb-exclusion-pause-test.log"
"=== LB exclusion test (docker pause) at $(Get-Date -Format o) ===" | Out-File $out
"CHAT_ID=$CHAT_ID" | Add-Content $out
# 3. Замеры ДО паузы
"`n--- ДО ПАУЗЫ (трафик идет на обе реплики) ---" | Add-Content $out
for ($i = 1; $i -le 4; $i++) {
$r = curl.exe -s -o NUL -w "HTTP=%{http_code} time=%{time_total}s" -X POST "http://127.0.0.1:8080/api/v1/chats/$CHAT_ID/messages" -H "Authorization: Bearer $TOKEN" -H "Idempotency-Key: pre-$i-$(New-Guid)" -H "Content-Type: application/json" -d '{\"text\":\"pre\"}'
Write-Host "Pre: $r"
"${i}: ${r}" | Add-Content $out
}
# 4. Замораживаем api-1
"`n---> docker pause lab3-api-1 (имитация зависшего пула)" | Add-Content $out
docker pause lab3-api-1
Write-Host "api-1 PAUSED"
# 5. Замеры ВО ВРЕМЯ паузы (проверяем non_idempotent)
"`n--- ВО ВРЕМЯ ПАУЗЫ (Nginx должен перекинуть на api-2) ---" | Add-Content $out
for ($i = 1; $i -le 6; $i++) {
# Ставим таймаут curl 15s, чтобы он не оборвался раньше Nginx (у nginx read_timeout 10s)
$r = curl.exe -s -o NUL -w "HTTP=%{http_code} time=%{time_total}s" -m 15 -X POST "http://127.0.0.1:8080/api/v1/chats/$CHAT_ID/messages" -H "Authorization: Bearer $TOKEN" -H "Idempotency-Key: during-$i-$(New-Guid)" -H "Content-Type: application/json" -d '{\"text\":\"during\"}'
Write-Host "During: $r"
"${i}: ${r}" | Add-Content $out
}
# 6. Размораживаем api-1
"`n---> docker unpause lab3-api-1" | Add-Content $out
docker unpause lab3-api-1
Write-Host "api-1 UNPAUSED"
# 7. Замеры ПОСЛЕ паузы
"`n--- ПОСЛЕ ПАУЗЫ ---" | Add-Content $out
for ($i = 1; $i -le 4; $i++) {
$r = curl.exe -s -o NUL -w "HTTP=%{http_code} time=%{time_total}s" -X POST "http://127.0.0.1:8080/api/v1/chats/$CHAT_ID/messages" -H "Authorization: Bearer $TOKEN" -H "Idempotency-Key: post-$i-$(New-Guid)" -H "Content-Type: application/json" -d '{\"text\":\"post\"}'
Write-Host "Post: $r"
"${i}: ${r}" | Add-Content $out
}
Write-Host "`n✅ Готово! Лог сохранен в $out"