Исследовать стоимость наблюдаемости и выбрать sampling
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
param(
|
||||
[string]$BaseUrl = "http://127.0.0.1:18080",
|
||||
[string]$EnvFile = ".env",
|
||||
[int]$LoadSeconds = 45,
|
||||
[int]$Concurrency = 4,
|
||||
[int]$WarmupSeconds = 10,
|
||||
[int]$StatsIntervalSeconds = 5
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
|
||||
$evidenceDir = Join-Path $project "evidence\lab6-$stamp-observability-cost"
|
||||
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null
|
||||
|
||||
$modes = @(
|
||||
[ordered]@{ name = "off"; sdk_disabled = $true; sampler_arg = 0.0; metric_interval_ms = 60000 },
|
||||
[ordered]@{ name = "full"; sdk_disabled = $false; sampler_arg = 1.0; metric_interval_ms = 10000 },
|
||||
[ordered]@{ name = "economy"; sdk_disabled = $false; sampler_arg = 0.05; metric_interval_ms = 60000 },
|
||||
[ordered]@{ name = "balanced"; sdk_disabled = $false; sampler_arg = 0.25; metric_interval_ms = 30000 }
|
||||
)
|
||||
|
||||
function Query-PrometheusScalar([string]$expression) {
|
||||
$encoded = [uri]::EscapeDataString($expression)
|
||||
$response = Invoke-RestMethod "http://127.0.0.1:9090/api/v1/query?query=$encoded"
|
||||
if (@($response.data.result).Count -eq 0) { return 0.0 }
|
||||
return [double]$response.data.result[0].value[1]
|
||||
}
|
||||
|
||||
function Query-TextMetric([string]$url, [string]$metricName) {
|
||||
$content = (Invoke-WebRequest -UseBasicParsing $url).Content
|
||||
$sum = 0.0
|
||||
foreach ($line in ($content -split "`n")) {
|
||||
if ($line -match ('^' + [regex]::Escape($metricName) + '(?:\{[^}]*\})?\s+([0-9.eE+\-]+)\s*$')) {
|
||||
$sum += [double]::Parse($Matches[1], [Globalization.CultureInfo]::InvariantCulture)
|
||||
}
|
||||
}
|
||||
return $sum
|
||||
}
|
||||
|
||||
function Capture-IngestCounters {
|
||||
return [ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
collector_accepted_spans = Query-PrometheusScalar 'sum(otelcol_receiver_accepted_spans_total) or vector(0)'
|
||||
collector_accepted_logs = Query-PrometheusScalar 'sum(otelcol_receiver_accepted_log_records_total) or vector(0)'
|
||||
collector_accepted_metric_points = Query-PrometheusScalar 'sum(otelcol_receiver_accepted_metric_points_total) or vector(0)'
|
||||
collector_sent_spans = Query-PrometheusScalar 'sum(otelcol_exporter_sent_spans_total) or vector(0)'
|
||||
collector_sent_logs = Query-PrometheusScalar 'sum(otelcol_exporter_sent_log_records_total) or vector(0)'
|
||||
collector_failed_spans = Query-PrometheusScalar 'sum(otelcol_exporter_send_failed_spans_total) or vector(0)'
|
||||
collector_failed_logs = Query-PrometheusScalar 'sum(otelcol_exporter_send_failed_log_records_total) or vector(0)'
|
||||
collector_enqueue_failed_spans = Query-PrometheusScalar 'sum(otelcol_exporter_enqueue_failed_spans_total) or vector(0)'
|
||||
collector_refused_spans = Query-PrometheusScalar 'sum(otelcol_receiver_refused_spans_total) or vector(0)'
|
||||
tempo_ingest_bytes = Query-TextMetric 'http://127.0.0.1:3200/metrics' 'tempo_distributor_bytes_received_total'
|
||||
tempo_ingest_spans = Query-TextMetric 'http://127.0.0.1:3200/metrics' 'tempo_distributor_spans_received_total'
|
||||
loki_line_bytes = Query-TextMetric 'http://127.0.0.1:3100/metrics' 'loki_distributor_bytes_received_total'
|
||||
loki_metadata_bytes = Query-TextMetric 'http://127.0.0.1:3100/metrics' 'loki_distributor_structured_metadata_bytes_received_total'
|
||||
loki_lines = Query-TextMetric 'http://127.0.0.1:3100/metrics' 'loki_distributor_lines_received_total'
|
||||
prometheus_appended_samples = Query-PrometheusScalar 'sum(prometheus_tsdb_head_samples_appended_total) or vector(0)'
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-MemoryToBytes([string]$value) {
|
||||
if ($value -notmatch '^([0-9.]+)\s*([KMG]iB)$') { return 0L }
|
||||
$number = [double]::Parse($Matches[1], [Globalization.CultureInfo]::InvariantCulture)
|
||||
$factor = switch ($Matches[2]) {
|
||||
'KiB' { 1KB }
|
||||
'MiB' { 1MB }
|
||||
'GiB' { 1GB }
|
||||
}
|
||||
return [long]($number * $factor)
|
||||
}
|
||||
|
||||
function Wait-ApiReady {
|
||||
$deadline = (Get-Date).AddMinutes(4)
|
||||
do {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 "$BaseUrl/health/ready"
|
||||
if ($response.StatusCode -eq 200) { return }
|
||||
}
|
||||
catch { Start-Sleep -Seconds 2 }
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
throw "API did not become ready at $BaseUrl"
|
||||
}
|
||||
|
||||
function Capture-ContainerStats([hashtable]$containerNames) {
|
||||
$names = @($containerNames.Values)
|
||||
$rows = @(docker stats --no-stream --format '{{json .}}' $names | ForEach-Object { $_ | ConvertFrom-Json })
|
||||
$captured = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
$result = @()
|
||||
foreach ($service in $containerNames.Keys) {
|
||||
$name = $containerNames[$service]
|
||||
$row = @($rows | Where-Object { $_.Name -eq $name })[0]
|
||||
if ($null -eq $row) { continue }
|
||||
$used = ($row.MemUsage -split '/')[0].Trim()
|
||||
$cpu = [double]::Parse(($row.CPUPerc -replace '%','').Trim(), [Globalization.CultureInfo]::InvariantCulture)
|
||||
$result += [pscustomobject][ordered]@{
|
||||
captured_at = $captured
|
||||
service = $service
|
||||
cpu_percent = $cpu
|
||||
memory_bytes = Convert-MemoryToBytes $used
|
||||
memory_display = $used
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
function Delta([object]$before, [object]$after, [string]$property) {
|
||||
return [double]$after.$property - [double]$before.$property
|
||||
}
|
||||
|
||||
function Summarize-Stats([object[]]$samples, [string]$service) {
|
||||
$selected = @($samples | Where-Object { $_.service -eq $service })
|
||||
if ($selected.Count -eq 0) {
|
||||
return [ordered]@{ sample_count = 0; cpu_avg_percent = 0; cpu_peak_percent = 0; ram_avg_bytes = 0; ram_peak_bytes = 0 }
|
||||
}
|
||||
$cpu = $selected | Measure-Object -Property cpu_percent -Average -Maximum
|
||||
$ram = $selected | Measure-Object -Property memory_bytes -Average -Maximum
|
||||
return [ordered]@{
|
||||
sample_count = $selected.Count
|
||||
cpu_avg_percent = [Math]::Round($cpu.Average, 3)
|
||||
cpu_peak_percent = [Math]::Round($cpu.Maximum, 3)
|
||||
ram_avg_bytes = [long]$ram.Average
|
||||
ram_peak_bytes = [long]$ram.Maximum
|
||||
}
|
||||
}
|
||||
|
||||
$modeResults = @()
|
||||
$loadJob = $null
|
||||
Push-Location $project
|
||||
try {
|
||||
foreach ($mode in $modes) {
|
||||
Write-Host "=== mode=$($mode.name) sdk_disabled=$($mode.sdk_disabled) sampler=$($mode.sampler_arg) metrics_ms=$($mode.metric_interval_ms) ==="
|
||||
$env:OTEL_SDK_DISABLED = $mode.sdk_disabled.ToString().ToLowerInvariant()
|
||||
$env:OTEL_TRACES_SAMPLER = 'parentbased_traceidratio'
|
||||
$env:OTEL_TRACES_SAMPLER_ARG = [string]$mode.sampler_arg
|
||||
$env:OTEL_METRIC_EXPORT_INTERVAL = [string]$mode.metric_interval_ms
|
||||
|
||||
docker compose --env-file $EnvFile up -d --no-deps --force-recreate api worker | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "compose recreate failed for $($mode.name)" }
|
||||
Wait-ApiReady
|
||||
|
||||
$warmupFile = Join-Path $evidenceDir "$($mode.name)-warmup.json"
|
||||
& python tests/load.py --base-url $BaseUrl --duration $WarmupSeconds --concurrency 2 --output $warmupFile | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "warm-up failed for $($mode.name)" }
|
||||
Start-Sleep -Seconds 12
|
||||
|
||||
$before = Capture-IngestCounters
|
||||
$containerNames = @{}
|
||||
foreach ($service in @('api','worker','otel-collector')) {
|
||||
$id = docker compose --env-file $EnvFile ps -q $service
|
||||
if (-not $id) { throw "container is missing for $service" }
|
||||
$containerNames[$service] = (docker inspect --format '{{.Name}}' $id).TrimStart('/')
|
||||
}
|
||||
|
||||
$loadFile = Join-Path $evidenceDir "$($mode.name)-load.json"
|
||||
$loadJob = Start-Job -ArgumentList $project,$BaseUrl,$LoadSeconds,$Concurrency,$loadFile -ScriptBlock {
|
||||
param($projectPath,$url,$duration,$workers,$outputPath)
|
||||
Set-Location $projectPath
|
||||
$env:PYTHONUTF8 = "1"
|
||||
& python tests/load.py --base-url $url --duration $duration --concurrency $workers --output $outputPath
|
||||
[pscustomobject]@{ exit_code = $LASTEXITCODE }
|
||||
}
|
||||
|
||||
$samples = @()
|
||||
while ($loadJob.State -in @('NotStarted','Running')) {
|
||||
$samples += Capture-ContainerStats $containerNames
|
||||
Start-Sleep -Seconds $StatsIntervalSeconds
|
||||
}
|
||||
$jobOutput = @(Receive-Job $loadJob)
|
||||
$exitRecord = @($jobOutput | Where-Object { $_.PSObject.Properties.Name -contains 'exit_code' })[-1]
|
||||
if ($null -eq $exitRecord -or $exitRecord.exit_code -ne 0) { throw "load failed for $($mode.name)" }
|
||||
Remove-Job $loadJob
|
||||
$loadJob = $null
|
||||
|
||||
Start-Sleep -Seconds 12
|
||||
$after = Capture-IngestCounters
|
||||
$load = Get-Content $loadFile -Raw | ConvertFrom-Json
|
||||
$delta = [ordered]@{}
|
||||
foreach ($property in @(
|
||||
'collector_accepted_spans','collector_accepted_logs','collector_accepted_metric_points',
|
||||
'collector_sent_spans','collector_sent_logs','collector_failed_spans','collector_failed_logs',
|
||||
'collector_enqueue_failed_spans','collector_refused_spans','tempo_ingest_bytes','tempo_ingest_spans',
|
||||
'loki_line_bytes','loki_metadata_bytes','loki_lines','prometheus_appended_samples')) {
|
||||
$delta[$property] = Delta $before $after $property
|
||||
}
|
||||
$delta['loki_total_bytes'] = $delta.loki_line_bytes + $delta.loki_metadata_bytes
|
||||
$delta['backend_total_bytes'] = $delta.tempo_ingest_bytes + $delta.loki_total_bytes
|
||||
|
||||
$modeResult = [ordered]@{
|
||||
mode = $mode
|
||||
load = $load
|
||||
ingest_before = $before
|
||||
ingest_after = $after
|
||||
ingest_delta = $delta
|
||||
resources = [ordered]@{
|
||||
api = Summarize-Stats $samples 'api'
|
||||
worker = Summarize-Stats $samples 'worker'
|
||||
collector = Summarize-Stats $samples 'otel-collector'
|
||||
}
|
||||
}
|
||||
$modeResult | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 (Join-Path $evidenceDir "$($mode.name)-result.json")
|
||||
$samples | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 (Join-Path $evidenceDir "$($mode.name)-resource-samples.json")
|
||||
$modeResults += $modeResult
|
||||
}
|
||||
|
||||
$full = @($modeResults | Where-Object { $_.mode.name -eq 'full' })[0]
|
||||
$off = @($modeResults | Where-Object { $_.mode.name -eq 'off' })[0]
|
||||
$fullSpansPerRequest = [double]$full.ingest_delta.collector_accepted_spans / [Math]::Max(1, [double]$full.load.successful_requests)
|
||||
$comparison = @()
|
||||
foreach ($result in $modeResults) {
|
||||
$requests = [double]$result.load.successful_requests
|
||||
$spansPerRequest = [double]$result.ingest_delta.collector_accepted_spans / [Math]::Max(1, $requests)
|
||||
$expectedAtFull = $fullSpansPerRequest * $requests
|
||||
$notEmitted = [Math]::Max(0, $expectedAtFull - [double]$result.ingest_delta.collector_accepted_spans)
|
||||
$transportLost = [double]$result.ingest_delta.collector_failed_spans + [double]$result.ingest_delta.collector_enqueue_failed_spans + [double]$result.ingest_delta.collector_refused_spans
|
||||
$comparison += [pscustomobject][ordered]@{
|
||||
mode = $result.mode.name
|
||||
sdk_disabled = $result.mode.sdk_disabled
|
||||
trace_sample_ratio = $result.mode.sampler_arg
|
||||
metric_interval_ms = $result.mode.metric_interval_ms
|
||||
successful_requests = $result.load.successful_requests
|
||||
failed_requests = $result.load.failed_requests
|
||||
successful_rps = $result.load.successful_rps
|
||||
rps_change_vs_off_percent = [Math]::Round(100 * ([double]$result.load.successful_rps / [double]$off.load.successful_rps - 1), 2)
|
||||
latency_p50_ms = $result.load.successful_latency_ms.p50
|
||||
latency_p95_ms = $result.load.successful_latency_ms.p95
|
||||
latency_p99_ms = $result.load.successful_latency_ms.p99
|
||||
p95_change_vs_off_percent = [Math]::Round(100 * ([double]$result.load.successful_latency_ms.p95 / [double]$off.load.successful_latency_ms.p95 - 1), 2)
|
||||
api_cpu_avg_percent = $result.resources.api.cpu_avg_percent
|
||||
api_ram_peak_bytes = $result.resources.api.ram_peak_bytes
|
||||
worker_cpu_avg_percent = $result.resources.worker.cpu_avg_percent
|
||||
worker_ram_peak_bytes = $result.resources.worker.ram_peak_bytes
|
||||
collector_cpu_avg_percent = $result.resources.collector.cpu_avg_percent
|
||||
collector_ram_peak_bytes = $result.resources.collector.ram_peak_bytes
|
||||
accepted_spans = $result.ingest_delta.collector_accepted_spans
|
||||
accepted_logs = $result.ingest_delta.collector_accepted_logs
|
||||
accepted_metric_points = $result.ingest_delta.collector_accepted_metric_points
|
||||
spans_per_successful_request = [Math]::Round($spansPerRequest, 4)
|
||||
trace_retained_percent_of_full_normalized = if ($fullSpansPerRequest -gt 0) { [Math]::Round(100 * $spansPerRequest / $fullSpansPerRequest, 2) } else { 0 }
|
||||
estimated_spans_not_emitted_by_sdk = [Math]::Round($notEmitted, 0)
|
||||
collector_transport_lost_spans = $transportLost
|
||||
tempo_ingest_bytes = $result.ingest_delta.tempo_ingest_bytes
|
||||
loki_ingest_bytes = $result.ingest_delta.loki_total_bytes
|
||||
backend_trace_and_log_ingest_bytes = $result.ingest_delta.backend_total_bytes
|
||||
tempo_bytes_per_successful_request = [Math]::Round([double]$result.ingest_delta.tempo_ingest_bytes / [Math]::Max(1, $requests), 2)
|
||||
loki_bytes_per_successful_request = [Math]::Round([double]$result.ingest_delta.loki_total_bytes / [Math]::Max(1, $requests), 2)
|
||||
backend_bytes_per_successful_request = [Math]::Round([double]$result.ingest_delta.backend_total_bytes / [Math]::Max(1, $requests), 2)
|
||||
prometheus_appended_samples = $result.ingest_delta.prometheus_appended_samples
|
||||
}
|
||||
}
|
||||
|
||||
$comparison | Export-Csv -NoTypeInformation -Encoding utf8 (Join-Path $evidenceDir 'comparison.csv')
|
||||
[ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
methodology = [ordered]@{
|
||||
load_seconds = $LoadSeconds
|
||||
concurrency = $Concurrency
|
||||
warmup_seconds = $WarmupSeconds
|
||||
stats_interval_seconds = $StatsIntervalSeconds
|
||||
workload = 'closed-loop POST messages; identical profile per mode; API and worker recreated before each mode'
|
||||
sampling_loss_definition = 'estimated against full-mode accepted spans per successful request; it is SDK non-emission, not Collector transport loss'
|
||||
ingest_units = 'Collector items; Tempo/Loki uncompressed backend bytes; Prometheus appended samples'
|
||||
}
|
||||
comparison = $comparison
|
||||
} | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 (Join-Path $evidenceDir 'summary.json')
|
||||
|
||||
& make test BASE_URL=$BaseUrl PYTHON=python 2>&1 | Tee-Object -FilePath (Join-Path $evidenceDir 'balanced-make-test.txt') | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw 'make test failed with balanced telemetry' }
|
||||
Write-Host "Evidence: $evidenceDir"
|
||||
}
|
||||
finally {
|
||||
if ($null -ne $loadJob) { Stop-Job $loadJob -ErrorAction SilentlyContinue; Remove-Job $loadJob -Force -ErrorAction SilentlyContinue }
|
||||
Remove-Item Env:OTEL_SDK_DISABLED -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:OTEL_TRACES_SAMPLER -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:OTEL_TRACES_SAMPLER_ARG -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:OTEL_METRIC_EXPORT_INTERVAL -ErrorAction SilentlyContinue
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
param(
|
||||
[string]$BaseUrl = "http://127.0.0.1:18080",
|
||||
[string]$EnvFile = ".env",
|
||||
[int]$RequestCount = 40,
|
||||
[string]$OutputFile = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
if (-not $OutputFile) {
|
||||
$OutputFile = Join-Path $project "evidence\head-sampling-probe.json"
|
||||
}
|
||||
|
||||
function Get-TempoStatus([string]$traceId) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 10 "http://127.0.0.1:3200/api/traces/$traceId"
|
||||
return [int]$response.StatusCode
|
||||
}
|
||||
catch {
|
||||
if ($_.Exception.Response) { return [int]$_.Exception.Response.StatusCode }
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
Push-Location $project
|
||||
try {
|
||||
$apiId = docker compose --env-file $EnvFile ps -q api
|
||||
if (-not $apiId) { throw 'API container is not running' }
|
||||
$since = [DateTimeOffset]::UtcNow.AddSeconds(-2)
|
||||
$statuses = @{}
|
||||
for ($i = 0; $i -lt $RequestCount; $i++) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 "$BaseUrl/health/not-found"
|
||||
$status = [int]$response.StatusCode
|
||||
}
|
||||
catch {
|
||||
$status = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 }
|
||||
}
|
||||
$key = [string]$status
|
||||
$statuses[$key] = 1 + [int]$statuses[$key]
|
||||
}
|
||||
|
||||
Start-Sleep -Seconds 15
|
||||
$rawLogs = @(docker logs --since $since.ToString('o') $apiId 2>&1)
|
||||
$events = @()
|
||||
foreach ($line in $rawLogs) {
|
||||
$text = [string]$line
|
||||
$jsonStart = $text.IndexOf('{')
|
||||
if ($jsonStart -lt 0) { continue }
|
||||
try { $entry = $text.Substring($jsonStart) | ConvertFrom-Json } catch { continue }
|
||||
if ($entry.event -eq 'http_request_completed' -and [int]$entry.'http.response.status_code' -eq 500) {
|
||||
$flags = [Convert]::ToInt32([string]$entry.trace_flags, 16)
|
||||
$events += [pscustomobject]@{
|
||||
trace_id = [string]$entry.trace_id
|
||||
sampled = (($flags -band 1) -eq 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$sampled = @($events | Where-Object sampled)
|
||||
$unsampled = @($events | Where-Object { -not $_.sampled })
|
||||
if ($sampled.Count -eq 0 -or $unsampled.Count -eq 0) {
|
||||
throw "Expected both sampled and unsampled 500 events; sampled=$($sampled.Count), unsampled=$($unsampled.Count)"
|
||||
}
|
||||
$sampledId = $sampled[0].trace_id
|
||||
$unsampledId = $unsampled[0].trace_id
|
||||
$result = [ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString('o')
|
||||
request_count = $RequestCount
|
||||
response_status_counts = $statuses
|
||||
correlated_log_count = $events.Count
|
||||
sampled_log_count = $sampled.Count
|
||||
unsampled_log_count = $unsampled.Count
|
||||
sampled_ratio = [Math]::Round($sampled.Count / [double]$events.Count, 4)
|
||||
sampled_example = [ordered]@{
|
||||
trace_id = $sampledId
|
||||
tempo_http_status = Get-TempoStatus $sampledId
|
||||
}
|
||||
unsampled_example = [ordered]@{
|
||||
trace_id = $unsampledId
|
||||
tempo_http_status = Get-TempoStatus $unsampledId
|
||||
}
|
||||
interpretation = 'Head sampling is decided before the HTTP outcome: a non-2xx log can exist even when its trace was not emitted to Tempo.'
|
||||
}
|
||||
$parent = Split-Path -Parent $OutputFile
|
||||
New-Item -ItemType Directory -Force -Path $parent | Out-Null
|
||||
$result | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 $OutputFile
|
||||
$result | ConvertTo-Json -Depth 10
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
Reference in New Issue
Block a user