ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
@@ -0,0 +1,700 @@
|
||||
// Command loadgen is a synthetic HTTP load generator for the lab3 experiment.
|
||||
// It is not part of the public API contract. It creates its own synthetic user
|
||||
// and chat through the load balancer, then measures message POST throughput
|
||||
// (or a mixed read/write profile) with per-second buckets and X-Instance-Id
|
||||
// attribution.
|
||||
//
|
||||
// The default profile is closed-loop: `-concurrency` workers each send the
|
||||
// next request as soon as the previous one finishes. `-rate` switches to an
|
||||
// open-loop target rate. Both are reported honestly as HTTP acknowledgement
|
||||
// throughput, not as a count of PostgreSQL commits.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
type config struct {
|
||||
baseURL string
|
||||
duration time.Duration
|
||||
warmup time.Duration
|
||||
concurrency int
|
||||
rate float64
|
||||
readRatio float64
|
||||
timeout time.Duration
|
||||
output string
|
||||
retryUncertain bool
|
||||
note string
|
||||
stopInstance string
|
||||
stopScript string
|
||||
stopAfter time.Duration
|
||||
}
|
||||
|
||||
type seriesBucket struct {
|
||||
Second int64 `json:"second"`
|
||||
Success int64 `json:"success"`
|
||||
Errors int64 `json:"errors"`
|
||||
P50 float64 `json:"p50_ms"`
|
||||
P95 float64 `json:"p95_ms"`
|
||||
P99 float64 `json:"p99_ms"`
|
||||
latency []float64
|
||||
}
|
||||
|
||||
type summary struct {
|
||||
Tool string `json:"tool"`
|
||||
Version string `json:"version"`
|
||||
StartedAt string `json:"started_at"`
|
||||
FinishedAt string `json:"finished_at"`
|
||||
MeasuredSeconds float64 `json:"measured_seconds"`
|
||||
WarmupSeconds float64 `json:"warmup_seconds"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
RateLimit float64 `json:"rate_limit_per_second"`
|
||||
ReadRatio float64 `json:"read_ratio"`
|
||||
RetryUncertain bool `json:"retry_uncertain"`
|
||||
Profile string `json:"profile"`
|
||||
Successful int64 `json:"successful_requests"`
|
||||
Failed int64 `json:"failed_requests"`
|
||||
ErrorRatio float64 `json:"error_ratio"`
|
||||
SuccessfulRPS float64 `json:"successful_rps"`
|
||||
OfferedRPS float64 `json:"offered_rps"`
|
||||
LatencyMS latencySummary `json:"successful_latency_ms"`
|
||||
StatusCounts map[string]int64 `json:"status_counts"`
|
||||
Instances map[string]int64 `json:"instances"`
|
||||
AppVersions map[string]int64 `json:"app_versions"`
|
||||
Kinds map[string]int64 `json:"kinds"`
|
||||
Series []seriesBucket `json:"series"`
|
||||
Retries int64 `json:"uncertain_retries"`
|
||||
Violations []string `json:"idempotency_violations,omitempty"`
|
||||
Note string `json:"note"`
|
||||
Failover *failoverSummary `json:"failover,omitempty"`
|
||||
}
|
||||
|
||||
type failoverSummary struct {
|
||||
TargetInstance string `json:"target_instance"`
|
||||
StopStartedAt string `json:"stop_started_at"`
|
||||
StopFinishedAt string `json:"stop_finished_at"`
|
||||
StopScriptExit int `json:"stop_script_exit"`
|
||||
StopDurationSeconds float64 `json:"stop_duration_seconds"`
|
||||
FirstSuccessAfterStopSec float64 `json:"first_success_after_stop_seconds"`
|
||||
FirstWriteAfterStopSec float64 `json:"first_write_after_stop_seconds"`
|
||||
FirstOtherSuccessSec float64 `json:"first_success_on_other_replica_seconds"`
|
||||
SuccessesAfterStop int64 `json:"successes_after_stop"`
|
||||
OtherSuccessesAfterStop int64 `json:"successes_on_other_replica_after_stop"`
|
||||
ErrorsAfterStop int64 `json:"errors_after_stop"`
|
||||
TargetResponsesAfterStop int64 `json:"target_responses_after_stop"`
|
||||
TargetLastResponseAt string `json:"target_last_response_at"`
|
||||
}
|
||||
|
||||
type latencySummary struct {
|
||||
P50 float64 `json:"p50"`
|
||||
P95 float64 `json:"p95"`
|
||||
P99 float64 `json:"p99"`
|
||||
Max float64 `json:"max"`
|
||||
Mean float64 `json:"mean"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
cfg := config{}
|
||||
flag.StringVar(&cfg.baseURL, "base-url", "http://127.0.0.1:8083", "LB base URL")
|
||||
flag.DurationVar(&cfg.duration, "duration", 20*time.Second, "measured duration")
|
||||
flag.DurationVar(&cfg.warmup, "warmup", 5*time.Second, "warmup before measurement")
|
||||
flag.IntVar(&cfg.concurrency, "concurrency", 32, "workers (closed loop) or max in-flight (rate mode)")
|
||||
flag.Float64Var(&cfg.rate, "rate", 0, "open-loop target requests/second; 0 = closed loop")
|
||||
flag.Float64Var(&cfg.readRatio, "read-ratio", 0, "fraction of GET /users/me requests (failover probe)")
|
||||
flag.DurationVar(&cfg.timeout, "timeout", 5*time.Second, "per-request timeout")
|
||||
flag.StringVar(&cfg.output, "output", "", "write JSON summary to this path")
|
||||
flag.BoolVar(&cfg.retryUncertain, "retry-uncertain", false, "retry failed POSTs with the same Idempotency-Key (failover probe)")
|
||||
flag.StringVar(&cfg.note, "note", "", "free-form note stored in the summary")
|
||||
flag.StringVar(&cfg.stopInstance, "stop-instance", "", "failover probe: stop this X-Instance-Id during the run")
|
||||
flag.StringVar(&cfg.stopScript, "stop-script", "", "failover probe: executable that stops TARGET_INSTANCE_ID")
|
||||
flag.DurationVar(&cfg.stopAfter, "stop-after", 0, "failover probe: stop after this much measured time")
|
||||
flag.StringVar(&version, "version", "dev", "generator revision label")
|
||||
flag.Parse()
|
||||
if cfg.duration <= 0 || cfg.concurrency < 1 || cfg.readRatio < 0 || cfg.readRatio > 1 || cfg.rate < 0 {
|
||||
fmt.Fprintln(os.Stderr, "invalid load parameters")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: cfg.timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: cfg.concurrency*2 + 8,
|
||||
MaxIdleConnsPerHost: cfg.concurrency*2 + 8,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
DisableCompression: true,
|
||||
},
|
||||
}
|
||||
actor, chat := bootstrap(client, cfg.baseURL)
|
||||
runID := randomHex(8)
|
||||
measureStart := time.Now().Add(cfg.warmup)
|
||||
deadline := measureStart.Add(cfg.duration)
|
||||
var failover *failoverState
|
||||
if cfg.stopScript != "" {
|
||||
target := cfg.stopInstance
|
||||
if target == "" {
|
||||
target = observeAnyInstance(client, cfg.baseURL, actor)
|
||||
}
|
||||
if target == "" {
|
||||
fail("no X-Instance-Id observed for failover target")
|
||||
}
|
||||
failover = &failoverState{target: target, script: cfg.stopScript}
|
||||
go failover.run(measureStart.Add(cfg.stopAfter))
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
samples []result
|
||||
series = map[int64]*seriesBucket{}
|
||||
retries int64
|
||||
)
|
||||
|
||||
worker := func(id int) {
|
||||
seq := 0
|
||||
for {
|
||||
now := time.Now()
|
||||
if !now.Before(deadline) {
|
||||
return
|
||||
}
|
||||
// Warmup traffic is sent but excluded from every summary number.
|
||||
measured := !now.Before(measureStart)
|
||||
kind := "write"
|
||||
if cfg.readRatio > 0 && float64((id+seq)%1000)/1000.0 < cfg.readRatio {
|
||||
kind = "read"
|
||||
}
|
||||
start := time.Now()
|
||||
result := oneRequest(client, cfg.baseURL, actor, chat, kind, fmt.Sprintf("%s-%d-%d", runID, id, seq), cfg.retryUncertain)
|
||||
elapsed := time.Since(start)
|
||||
seq++
|
||||
if !measured {
|
||||
continue
|
||||
}
|
||||
result.at = start
|
||||
result.done = time.Now()
|
||||
result.latency = elapsed
|
||||
mu.Lock()
|
||||
samples = append(samples, result)
|
||||
if result.err != "" && result.ok {
|
||||
retries++
|
||||
}
|
||||
bucket := series[start.Unix()]
|
||||
if bucket == nil {
|
||||
bucket = &seriesBucket{Second: start.Unix()}
|
||||
series[start.Unix()] = bucket
|
||||
}
|
||||
if result.ok {
|
||||
bucket.Success++
|
||||
bucket.latency = append(bucket.latency, float64(result.latency.Microseconds())/1000.0)
|
||||
} else {
|
||||
bucket.Errors++
|
||||
}
|
||||
mu.Unlock()
|
||||
if cfg.rate > 0 {
|
||||
// Spread a fixed offered rate across workers. This is a
|
||||
// best-effort pacing, not a hard scheduler; lateness is
|
||||
// visible in the latency distribution.
|
||||
interval := time.Duration(float64(time.Second) * float64(cfg.concurrency) / cfg.rate)
|
||||
if sleep := interval - time.Since(start); sleep > 0 {
|
||||
time.Sleep(sleep)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < cfg.concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
worker(id)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
finished := time.Now()
|
||||
measuredSeconds := finished.Sub(measureStart).Seconds()
|
||||
|
||||
var failoverSnapshot *failoverState
|
||||
if failover != nil {
|
||||
failoverSnapshot = failover
|
||||
}
|
||||
sum := summarize(cfg, runID, measureStart, finished, measuredSeconds, samples, series, atomic.LoadInt64(&retries), failoverSnapshot)
|
||||
if cfg.output != "" {
|
||||
data, _ := json.MarshalIndent(sum, "", " ")
|
||||
if err := os.WriteFile(cfg.output, append(data, '\n'), 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cannot write output:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
encoded, _ := json.MarshalIndent(sum, "", " ")
|
||||
fmt.Println(string(encoded))
|
||||
if sum.Successful == 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
token string
|
||||
user string
|
||||
}
|
||||
|
||||
type chatInfo struct {
|
||||
id string
|
||||
}
|
||||
|
||||
type result struct {
|
||||
at time.Time
|
||||
done time.Time
|
||||
latency time.Duration
|
||||
ok bool
|
||||
status int
|
||||
instance string
|
||||
appVer string
|
||||
kind string
|
||||
key string
|
||||
message string
|
||||
err string
|
||||
}
|
||||
|
||||
func oneRequest(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string, retry bool) result {
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
res := requestOnce(client, base, actor, chat, kind, key)
|
||||
if res.ok || !retry || kind != "write" || time.Now().After(deadline) {
|
||||
return res
|
||||
}
|
||||
// A timeout or LB 502/503 after SIGTERM is an uncertain result. The
|
||||
// same key is safe to retry only because the server's idempotency
|
||||
// record and message are committed atomically.
|
||||
res.err = "retry:" + res.err
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func requestOnce(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string) result {
|
||||
method, path := http.MethodPost, "/api/v1/chats/"+chat.id+"/messages"
|
||||
var body io.Reader
|
||||
if kind == "read" {
|
||||
method, path = http.MethodGet, "/api/v1/users/me"
|
||||
} else {
|
||||
payload, _ := json.Marshal(map[string]string{"text": "load " + key})
|
||||
body = bytes.NewReader(payload)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(context.Background(), method, base+path, body)
|
||||
if err != nil {
|
||||
return result{status: 0, err: "build_request"}
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+actor.token)
|
||||
if kind == "write" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return result{status: 0, err: "transport"}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, readErr := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
res := result{
|
||||
status: response.StatusCode,
|
||||
instance: response.Header.Get("X-Instance-Id"),
|
||||
appVer: response.Header.Get("X-App-Version"),
|
||||
kind: kind,
|
||||
key: key,
|
||||
}
|
||||
if readErr != nil {
|
||||
res.err = "read_body"
|
||||
return res
|
||||
}
|
||||
if response.StatusCode == http.StatusCreated || response.StatusCode == http.StatusOK {
|
||||
res.ok = true
|
||||
if kind == "write" {
|
||||
var message struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &message); err != nil || message.ID == "" {
|
||||
res.ok = false
|
||||
res.err = "bad_json"
|
||||
} else {
|
||||
res.message = message.ID
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
res.err = "status"
|
||||
return res
|
||||
}
|
||||
|
||||
func bootstrap(client *http.Client, base string) (credentials, chatInfo) {
|
||||
// /health/ready is retried until the stack is up.
|
||||
waitReady(client, base)
|
||||
username := "lg_" + randomHex(10)
|
||||
password := "Loadgen-" + randomHex(12)
|
||||
registered := struct {
|
||||
ID string `json:"id"`
|
||||
}{}
|
||||
postJSON(client, base+"/api/v1/users", "", map[string]string{
|
||||
"username": username, "display_name": "Load generator", "password": password,
|
||||
}, ®istered)
|
||||
basic := basicAuth(username, password)
|
||||
session := struct {
|
||||
Token string `json:"token"`
|
||||
}{}
|
||||
postJSON(client, base+"/api/v1/auth/sessions", "Basic "+basic, nil, &session)
|
||||
if session.Token == "" || registered.ID == "" {
|
||||
fail("bootstrap failed")
|
||||
}
|
||||
chat := struct {
|
||||
ID string `json:"id"`
|
||||
}{}
|
||||
postJSON(client, base+"/api/v1/chats", "Bearer "+session.Token, map[string]interface{}{
|
||||
"title": "loadgen " + randomHex(6), "member_ids": []string{registered.ID},
|
||||
}, &chat)
|
||||
if chat.ID == "" {
|
||||
fail("chat bootstrap failed")
|
||||
}
|
||||
return credentials{token: session.Token, user: registered.ID}, chatInfo{id: chat.ID}
|
||||
}
|
||||
|
||||
func waitReady(client *http.Client, base string) {
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
response, err := client.Get(base + "/health/ready")
|
||||
if err == nil {
|
||||
io.Copy(io.Discard, response.Body)
|
||||
response.Body.Close()
|
||||
if response.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
fail("stack did not become ready")
|
||||
}
|
||||
|
||||
func postJSON(client *http.Client, url, authorization string, body interface{}, out interface{}) {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
data, _ := json.Marshal(body)
|
||||
reader = bytes.NewReader(data)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, url, reader)
|
||||
if err != nil {
|
||||
fail("build bootstrap request")
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if authorization != "" {
|
||||
req.Header.Set("Authorization", authorization)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
fail("bootstrap transport failure")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
fail(fmt.Sprintf("bootstrap status %d", response.StatusCode))
|
||||
}
|
||||
if out != nil {
|
||||
if err := json.Unmarshal(data, out); err != nil {
|
||||
fail("bootstrap JSON")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func basicAuth(username, password string) string {
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
raw := []byte(username + ":" + password)
|
||||
var encoded []byte
|
||||
for i := 0; i < len(raw); i += 3 {
|
||||
var chunk [3]byte
|
||||
n := copy(chunk[:], raw[i:])
|
||||
value := uint(chunk[0])<<16 | uint(chunk[1])<<8 | uint(chunk[2])
|
||||
encoded = append(encoded, alphabet[value>>18&63], alphabet[value>>12&63])
|
||||
if n > 1 {
|
||||
encoded = append(encoded, alphabet[value>>6&63])
|
||||
} else {
|
||||
encoded = append(encoded, '=')
|
||||
}
|
||||
if n > 2 {
|
||||
encoded = append(encoded, alphabet[value&63])
|
||||
} else {
|
||||
encoded = append(encoded, '=')
|
||||
}
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func summarize(cfg config, runID string, start, finished time.Time, seconds float64, samples []result, series map[int64]*seriesBucket, retries int64, failover *failoverState) summary {
|
||||
sum := summary{
|
||||
Tool: "mtusi-lab3-loadgen",
|
||||
Version: version,
|
||||
StartedAt: start.UTC().Format(time.RFC3339Nano),
|
||||
FinishedAt: finished.UTC().Format(time.RFC3339Nano),
|
||||
MeasuredSeconds: round(seconds, 3),
|
||||
WarmupSeconds: cfg.warmup.Seconds(),
|
||||
Concurrency: cfg.concurrency,
|
||||
RateLimit: cfg.rate,
|
||||
ReadRatio: cfg.readRatio,
|
||||
RetryUncertain: cfg.retryUncertain,
|
||||
Profile: "closed-loop",
|
||||
StatusCounts: map[string]int64{},
|
||||
Instances: map[string]int64{},
|
||||
AppVersions: map[string]int64{},
|
||||
Kinds: map[string]int64{},
|
||||
Retries: retries,
|
||||
Note: cfg.note,
|
||||
}
|
||||
if cfg.rate > 0 {
|
||||
sum.Profile = fmt.Sprintf("open-loop target %.1f req/s (best effort)", cfg.rate)
|
||||
}
|
||||
sum.Note = cfg.note + "; synthetic messages created by loadgen, no retries unless -retry-uncertain"
|
||||
var latencies []float64
|
||||
idByKey := map[string]string{}
|
||||
summaryFailover := buildFailoverSummary(failover, samples)
|
||||
for _, item := range samples {
|
||||
sum.Kinds[item.kind]++
|
||||
statusKey := fmt.Sprintf("%d", item.status)
|
||||
if item.status == 0 {
|
||||
statusKey = "error:" + item.err
|
||||
}
|
||||
sum.StatusCounts[statusKey]++
|
||||
if item.ok {
|
||||
sum.Successful++
|
||||
latencies = append(latencies, float64(item.latency.Microseconds())/1000.0)
|
||||
if item.instance == "" {
|
||||
item.instance = "(missing)"
|
||||
}
|
||||
sum.Instances[item.instance]++
|
||||
ver := item.appVer
|
||||
if ver == "" {
|
||||
ver = "(missing)"
|
||||
}
|
||||
sum.AppVersions[ver]++
|
||||
if item.kind == "write" && item.message != "" {
|
||||
if previous, seen := idByKey[item.key]; seen && previous != item.message {
|
||||
sum.Violations = append(sum.Violations, "same key returned different message ids")
|
||||
}
|
||||
idByKey[item.key] = item.message
|
||||
}
|
||||
} else {
|
||||
sum.Failed++
|
||||
}
|
||||
}
|
||||
sum.OfferedRPS = round(float64(sum.Successful+sum.Failed)/seconds, 3)
|
||||
sum.SuccessfulRPS = round(float64(sum.Successful)/seconds, 3)
|
||||
if total := sum.Successful + sum.Failed; total > 0 {
|
||||
sum.ErrorRatio = round(float64(sum.Failed)/float64(total), 6)
|
||||
}
|
||||
sort.Float64s(latencies)
|
||||
sum.LatencyMS = latencyPercentiles(latencies)
|
||||
sum.Failover = summaryFailover
|
||||
keys := make([]int64, 0, len(series))
|
||||
for second := range series {
|
||||
keys = append(keys, second)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
|
||||
for _, second := range keys {
|
||||
bucket := series[second]
|
||||
sort.Float64s(bucket.latency)
|
||||
bucket.P50 = percentile(bucket.latency, 0.50)
|
||||
bucket.P95 = percentile(bucket.latency, 0.95)
|
||||
bucket.P99 = percentile(bucket.latency, 0.99)
|
||||
sum.Series = append(sum.Series, *bucket)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func percentile(sorted []float64, p float64) float64 {
|
||||
if len(sorted) == 0 {
|
||||
return 0
|
||||
}
|
||||
index := int(math.Ceil(p*float64(len(sorted)))) - 1
|
||||
if index < 0 {
|
||||
index = 0
|
||||
}
|
||||
if index >= len(sorted) {
|
||||
index = len(sorted) - 1
|
||||
}
|
||||
return round(sorted[index], 3)
|
||||
}
|
||||
|
||||
func latencyPercentiles(sorted []float64) latencySummary {
|
||||
if len(sorted) == 0 {
|
||||
return latencySummary{}
|
||||
}
|
||||
pick := func(p float64) float64 { return percentile(sorted, p) }
|
||||
var total float64
|
||||
for _, value := range sorted {
|
||||
total += value
|
||||
}
|
||||
return latencySummary{
|
||||
P50: pick(0.50), P95: pick(0.95), P99: pick(0.99),
|
||||
Max: round(sorted[len(sorted)-1], 3), Mean: round(total/float64(len(sorted)), 3),
|
||||
}
|
||||
}
|
||||
|
||||
func round(value float64, digits int) float64 {
|
||||
scale := math.Pow(10, float64(digits))
|
||||
return math.Round(value*scale) / scale
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
fail("random")
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
func fail(message string) {
|
||||
fmt.Fprintln(os.Stderr, "loadgen:", message)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
type failoverState struct {
|
||||
target string
|
||||
script string
|
||||
mu sync.Mutex
|
||||
started time.Time
|
||||
finished time.Time
|
||||
exitCode int
|
||||
err string
|
||||
}
|
||||
|
||||
func (f *failoverState) run(at time.Time) {
|
||||
if delay := time.Until(at); delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.started = time.Now()
|
||||
f.mu.Unlock()
|
||||
command := exec.Command(f.script)
|
||||
command.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+f.target)
|
||||
command.Stdout = io.Discard
|
||||
command.Stderr = io.Discard
|
||||
err := command.Run()
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.finished = time.Now()
|
||||
if err == nil {
|
||||
f.exitCode = 0
|
||||
return
|
||||
}
|
||||
if exitError, ok := err.(*exec.ExitError); ok {
|
||||
f.exitCode = exitError.ExitCode()
|
||||
} else {
|
||||
f.exitCode = -1
|
||||
f.err = err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *failoverState) snapshot() failoverState {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return failoverState{
|
||||
target: f.target,
|
||||
started: f.started,
|
||||
finished: f.finished,
|
||||
exitCode: f.exitCode,
|
||||
err: f.err,
|
||||
}
|
||||
}
|
||||
|
||||
func observeAnyInstance(client *http.Client, base string, actor credentials) string {
|
||||
deadline := time.Now().Add(30 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/users/me", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+actor.token)
|
||||
response, err := client.Do(req)
|
||||
if err == nil {
|
||||
io.Copy(io.Discard, response.Body)
|
||||
response.Body.Close()
|
||||
if instance := response.Header.Get("X-Instance-Id"); instance != "" {
|
||||
return instance
|
||||
}
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func buildFailoverSummary(failover *failoverState, samples []result) *failoverSummary {
|
||||
if failover == nil {
|
||||
return nil
|
||||
}
|
||||
state := failover.snapshot()
|
||||
if state.started.IsZero() {
|
||||
return nil
|
||||
}
|
||||
summary := &failoverSummary{
|
||||
TargetInstance: state.target,
|
||||
StopStartedAt: state.started.UTC().Format(time.RFC3339Nano),
|
||||
StopFinishedAt: state.finished.UTC().Format(time.RFC3339Nano),
|
||||
StopScriptExit: state.exitCode,
|
||||
StopDurationSeconds: round(state.finished.Sub(state.started).Seconds(), 3),
|
||||
FirstSuccessAfterStopSec: -1,
|
||||
FirstWriteAfterStopSec: -1,
|
||||
FirstOtherSuccessSec: -1,
|
||||
}
|
||||
var firstSuccess, firstWrite, firstOther time.Time
|
||||
var lastTarget time.Time
|
||||
for _, item := range samples {
|
||||
if item.instance == state.target && item.done.After(lastTarget) {
|
||||
lastTarget = item.done
|
||||
}
|
||||
if !item.at.After(state.started) {
|
||||
continue
|
||||
}
|
||||
if item.ok {
|
||||
summary.SuccessesAfterStop++
|
||||
if firstSuccess.IsZero() || item.done.Before(firstSuccess) {
|
||||
firstSuccess = item.done
|
||||
}
|
||||
if item.kind == "write" && (firstWrite.IsZero() || item.done.Before(firstWrite)) {
|
||||
firstWrite = item.done
|
||||
}
|
||||
if item.instance != state.target {
|
||||
summary.OtherSuccessesAfterStop++
|
||||
if firstOther.IsZero() || item.done.Before(firstOther) {
|
||||
firstOther = item.done
|
||||
}
|
||||
}
|
||||
} else {
|
||||
summary.ErrorsAfterStop++
|
||||
}
|
||||
if item.at.After(state.finished.Add(500*time.Millisecond)) && item.instance == state.target {
|
||||
summary.TargetResponsesAfterStop++
|
||||
}
|
||||
}
|
||||
if !firstSuccess.IsZero() {
|
||||
summary.FirstSuccessAfterStopSec = round(firstSuccess.Sub(state.started).Seconds(), 3)
|
||||
}
|
||||
if !firstWrite.IsZero() {
|
||||
summary.FirstWriteAfterStopSec = round(firstWrite.Sub(state.started).Seconds(), 3)
|
||||
}
|
||||
if !firstOther.IsZero() {
|
||||
summary.FirstOtherSuccessSec = round(firstOther.Sub(state.started).Seconds(), 3)
|
||||
}
|
||||
if !lastTarget.IsZero() {
|
||||
summary.TargetLastResponseAt = lastTarget.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
return summary
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// Command messenger runs the lab3 HTTP API and the container healthcheck
|
||||
// helper. PostgreSQL holds users, chats, membership, messages and idempotency
|
||||
// records; Valkey holds server-side sessions shared by every API replica.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/api"
|
||||
"mtusi.ru/messenger-lab4/internal/config"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
"mtusi.ru/messenger-lab4/internal/session"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
// Overridden at build time with -X main.version=... and -X main.revision=...
|
||||
var (
|
||||
version = "dev"
|
||||
revision = "unknown"
|
||||
)
|
||||
|
||||
const idempotencyRetention = 24 * time.Hour
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "probe the local liveness endpoint and exit 0/1")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(runHealthcheck(cfg))
|
||||
}
|
||||
|
||||
logger := newLogger(cfg)
|
||||
ctx := context.Background()
|
||||
instanceID := instanceIdentity()
|
||||
|
||||
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
|
||||
MaxConns: cfg.DBMaxConns,
|
||||
MinConns: cfg.DBMinConns,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("database configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
|
||||
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
|
||||
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
sessions, err := session.Open(cfg.CacheURL, session.Options{
|
||||
PoolSize: cfg.CachePoolSize,
|
||||
DialTimeout: cfg.CacheTimeout,
|
||||
IOTimeout: cfg.CacheTimeout,
|
||||
TTL: cfg.SessionTTL,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("session store configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
|
||||
objects, err := objectstore.Open(objectstore.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
Region: cfg.S3Region,
|
||||
Bucket: cfg.S3Bucket,
|
||||
AccessKey: cfg.S3AccessKey,
|
||||
SecretKey: cfg.S3SecretKey,
|
||||
Timeout: cfg.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("object store configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
app, err := api.New(repository, sessions, objects, logger, instanceID, version, api.Options{
|
||||
MaxUploadBytes: cfg.MaxUploadBytes,
|
||||
MaxImagePixels: cfg.MaxImagePixels,
|
||||
DecodeConcurrency: cfg.DecodeConcurrency,
|
||||
PutConcurrency: cfg.PutConcurrency,
|
||||
TempDir: cfg.TempDir,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("application initialization failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Handler: app.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 20 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
||||
listener, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
logger.Error("listen failed", "address", address, "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Operator-only stats listener. It is bound to container loopback by
|
||||
// default and is not published by compose, so it cannot bypass the LB.
|
||||
var metricsServer *http.Server
|
||||
if cfg.MetricsAddr != "off" {
|
||||
metricsMux := http.NewServeMux()
|
||||
metricsMux.HandleFunc("/internal/stats", app.InternalStatsHandler)
|
||||
metricsServer = &http.Server{
|
||||
Handler: metricsMux,
|
||||
ReadHeaderTimeout: 2 * time.Second,
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 5 * time.Second,
|
||||
}
|
||||
metricsListener, listenErr := net.Listen("tcp", cfg.MetricsAddr)
|
||||
if listenErr != nil {
|
||||
logger.Error("metrics listen failed", "address", cfg.MetricsAddr, "error", listenErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
go func() {
|
||||
if serveErr := metricsServer.Serve(metricsListener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
|
||||
logger.Error("metrics server stopped unexpectedly", "error", serveErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
pruneCtx, pruneCancel := context.WithCancel(ctx)
|
||||
defer pruneCancel()
|
||||
go pruneIdempotency(pruneCtx, repository, logger)
|
||||
|
||||
logger.Info("server listening",
|
||||
"address", listener.Addr().String(),
|
||||
"env", cfg.Env,
|
||||
"instance_id", instanceID,
|
||||
"version", version,
|
||||
"revision", revision,
|
||||
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
|
||||
"s3_bucket", cfg.S3Bucket,
|
||||
"max_upload_bytes", cfg.MaxUploadBytes,
|
||||
"max_image_pixels", cfg.MaxImagePixels,
|
||||
"decode_concurrency", cfg.DecodeConcurrency,
|
||||
"s3_put_concurrency", cfg.PutConcurrency,
|
||||
"shutdown_timeout_seconds", int(cfg.ShutdownTimeout.Seconds()),
|
||||
"shutdown_drain_seconds", int(cfg.ShutdownDrain.Seconds()),
|
||||
"db_max_conns", cfg.DBMaxConns,
|
||||
)
|
||||
|
||||
serveErrors := make(chan error, 1)
|
||||
go func() {
|
||||
serveErrors <- server.Serve(listener)
|
||||
}()
|
||||
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
select {
|
||||
case received := <-signals:
|
||||
logger.Info("shutdown initiated", "signal", received.String(), "instance_id", instanceID)
|
||||
// Stop advertising readiness first. The load balancer removes this
|
||||
// backend during the drain window while the process still accepts
|
||||
// requests, so in-flight work is not cut off by the health transition.
|
||||
app.SetReady(false)
|
||||
if cfg.ShutdownDrain > 0 {
|
||||
logger.Info("draining", "seconds", int(cfg.ShutdownDrain.Seconds()))
|
||||
time.Sleep(cfg.ShutdownDrain)
|
||||
}
|
||||
started := time.Now()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("graceful shutdown failed", "error", err)
|
||||
_ = server.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
if metricsServer != nil {
|
||||
_ = metricsServer.Close()
|
||||
}
|
||||
pruneCancel()
|
||||
logger.Info("shutdown complete",
|
||||
"instance_id", instanceID,
|
||||
"elapsed_ms", float64(time.Since(started).Microseconds())/1000.0,
|
||||
)
|
||||
os.Exit(0)
|
||||
case err := <-serveErrors:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.Error("server stopped unexpectedly", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// instanceIdentity is stable for the lifetime of this process and unique per
|
||||
// container. INSTANCE_ID overrides it; otherwise the container hostname is the
|
||||
// actual process identity, which lets scripts/stop-one.sh map an X-Instance-Id
|
||||
// response to exactly one Docker container. lab7 replaces this with an opaque
|
||||
// alias that does not reveal a hostname.
|
||||
func instanceIdentity() string {
|
||||
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
|
||||
return value
|
||||
}
|
||||
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
|
||||
return hostname
|
||||
}
|
||||
return uuid.NewRandom(8)
|
||||
}
|
||||
|
||||
func newLogger(cfg config.Config) *slog.Logger {
|
||||
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
|
||||
return slog.New(handler).With("service", "messenger-lab4", "app_env", cfg.Env)
|
||||
}
|
||||
|
||||
func waitForDatabase(ctx context.Context, repository *store.Store, timeout time.Duration, logger *slog.Logger) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
attempt := 0
|
||||
for {
|
||||
attempt++
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err := repository.Ping(pingCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return err
|
||||
}
|
||||
logger.Debug("waiting for postgres", "attempt", attempt, "error", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func pruneIdempotency(ctx context.Context, repository *store.Store, logger *slog.Logger) {
|
||||
run := func() {
|
||||
pruneCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
deleted, err := repository.PruneIdempotency(pruneCtx, idempotencyRetention)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
logger.Warn("idempotency prune failed", "error", err)
|
||||
return
|
||||
}
|
||||
if deleted > 0 {
|
||||
logger.Info("pruned expired idempotency records", "rows", deleted, "retention_hours", 24)
|
||||
}
|
||||
}
|
||||
run()
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runHealthcheck is compiled into the same binary as the server, so the
|
||||
// runtime image needs no curl, wget or shell. It always talks to loopback
|
||||
// inside the container, independently of APP_HOST.
|
||||
func runHealthcheck(cfg config.Config) int {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
|
||||
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
|
||||
return 1
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, response.Body)
|
||||
if response.StatusCode != http.StatusOK {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck status:", response.StatusCode)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Command migrate applies the embedded, checksummed PostgreSQL migrations and
|
||||
// exits. It is a separate one-shot compose service: API replicas never race to
|
||||
// migrate the shared schema. The advisory lock inside store.Migrate serialises
|
||||
// concurrent invocations of this command as well.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/config"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
var revision = "unknown"
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
|
||||
With("service", "messenger-lab4-migrate", "revision", revision)
|
||||
|
||||
cfg, err := config.LoadMigrate()
|
||||
if err != nil {
|
||||
logger.Error("configuration error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
|
||||
MaxConns: cfg.DBMaxConns,
|
||||
MinConns: 0,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("database configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
|
||||
for {
|
||||
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err = repository.Ping(pingCtx)
|
||||
pingCancel()
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
logger.Error("postgres did not become ready", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("waiting for postgres", "error", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
if err := repository.Migrate(ctx); err != nil {
|
||||
logger.Error("migrations failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("migrations complete", "elapsed_ms", float64(time.Since(started).Microseconds())/1000.0)
|
||||
fmt.Println("migrations: up-to-date")
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
// Command reconciler is the track-2 consistency tool for the two stores.
|
||||
//
|
||||
// It compares PostgreSQL attachment rows with the objects under the private
|
||||
// bucket prefix and reports:
|
||||
// - ready row + object -> ok
|
||||
// - ready row without object -> missing_object (report only: bytes
|
||||
// cannot be invented or safely replaced; the operator must restore them)
|
||||
// - pending row + object -> stale upload intent after the grace
|
||||
// period; the object and the row are both removed
|
||||
// - pending row without object -> stale upload intent; the row is removed
|
||||
// - object without a row -> orphan object; removed only after grace
|
||||
//
|
||||
// Fresh objects and rows are never touched: the grace period protects an
|
||||
// upload that is between its S3 PUT and its PostgreSQL COMMIT, and the
|
||||
// reconciler re-checks the database immediately before every delete.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/config"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
type item struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Status string `json:"status,omitempty"`
|
||||
AgeSeconds int64 `json:"age_seconds"`
|
||||
ObjectPresent bool `json:"object_present,omitempty"`
|
||||
}
|
||||
|
||||
type report struct {
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
Mode string `json:"mode"`
|
||||
Bucket string `json:"bucket"`
|
||||
Prefix string `json:"prefix"`
|
||||
GraceSeconds int64 `json:"grace_seconds"`
|
||||
Database dbCounts `json:"database"`
|
||||
ObjectStore s3Counts `json:"object_store"`
|
||||
Findings findings `json:"findings"`
|
||||
Actions actions `json:"actions"`
|
||||
Timing timing `json:"timing"`
|
||||
}
|
||||
|
||||
type dbCounts struct {
|
||||
Rows int `json:"rows"`
|
||||
Ready int `json:"ready"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
|
||||
type s3Counts struct {
|
||||
Objects int `json:"objects"`
|
||||
}
|
||||
|
||||
type findings struct {
|
||||
OK int `json:"ok"`
|
||||
OrphanObjects []item `json:"orphan_objects"`
|
||||
ProtectedObjects []item `json:"protected_recent_objects"`
|
||||
MissingObjects []item `json:"missing_objects"`
|
||||
StalePending []item `json:"stale_pending"`
|
||||
ProtectedPending []item `json:"protected_pending"`
|
||||
}
|
||||
|
||||
type actions struct {
|
||||
PlannedDeletes []string `json:"planned_deletes,omitempty"`
|
||||
DeletedObjects []string `json:"deleted_objects"`
|
||||
DeletedPendingRows []string `json:"deleted_pending_rows"`
|
||||
Skipped []string `json:"skipped"`
|
||||
UnresolvedMissing []string `json:"unresolved_missing"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
|
||||
type timing struct {
|
||||
DBScanMS int64 `json:"db_scan_ms"`
|
||||
S3ListMS int64 `json:"s3_list_ms"`
|
||||
TotalMS int64 `json:"total_ms"`
|
||||
DBRows int `json:"db_rows"`
|
||||
S3Objects int `json:"s3_objects"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "perform safe deletions; without it the run is a read-only dry run")
|
||||
prefix := flag.String("prefix", "attachments/", "bucket prefix owned by the application")
|
||||
output := flag.String("output", "", "optional path for the JSON report")
|
||||
defaultGrace := time.Hour
|
||||
if raw := os.Getenv("RECONCILE_GRACE_SECONDS"); raw != "" {
|
||||
seconds, err := strconv.Atoi(raw)
|
||||
if err != nil || seconds < 1 {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: RECONCILE_GRACE_SECONDS must be a positive integer")
|
||||
os.Exit(2)
|
||||
}
|
||||
defaultGrace = time.Duration(seconds) * time.Second
|
||||
}
|
||||
grace := flag.Duration("grace", defaultGrace, "minimum age before an orphan object or pending upload intent may be removed")
|
||||
flag.Parse()
|
||||
if *grace < time.Second {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: -grace must be at least 1s")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *prefix == "" || *prefix == "/" {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: -prefix must be a non-empty application prefix")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
cfg, err := config.LoadTool()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
repository, err := store.Open(context.Background(), cfg.DatabaseURL, store.Options{
|
||||
MaxConns: 4,
|
||||
MinConns: 0,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: database configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
objects, err := objectstore.Open(objectstore.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
Region: cfg.S3Region,
|
||||
Bucket: cfg.S3Bucket,
|
||||
AccessKey: cfg.S3AccessKey,
|
||||
SecretKey: cfg.S3SecretKey,
|
||||
Timeout: cfg.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: object store configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
started := time.Now().UTC()
|
||||
result := report{
|
||||
GeneratedAt: started.Format(time.RFC3339Nano),
|
||||
Mode: "dry-run",
|
||||
Bucket: cfg.S3Bucket,
|
||||
Prefix: *prefix,
|
||||
GraceSeconds: int64(grace.Seconds()),
|
||||
}
|
||||
if *apply {
|
||||
result.Mode = "apply"
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
dbStarted := time.Now()
|
||||
rows, err := repository.ListAttachmentsForReconcile(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: database scan failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result.Timing.DBScanMS = time.Since(dbStarted).Milliseconds()
|
||||
result.Timing.DBRows = len(rows)
|
||||
result.Database.Rows = len(rows)
|
||||
|
||||
s3Started := time.Now()
|
||||
stored, err := objects.List(ctx, *prefix)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: object store scan failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result.Timing.S3ListMS = time.Since(s3Started).Milliseconds()
|
||||
result.Timing.S3Objects = len(stored)
|
||||
result.ObjectStore.Objects = len(stored)
|
||||
|
||||
now := time.Now().UTC()
|
||||
dbByKey := make(map[string]store.ReconcileAttachment, len(rows))
|
||||
for _, row := range rows {
|
||||
dbByKey[row.ObjectKey] = row
|
||||
switch row.Status {
|
||||
case "ready":
|
||||
result.Database.Ready++
|
||||
case "pending":
|
||||
result.Database.Pending++
|
||||
}
|
||||
}
|
||||
objectByKey := make(map[string]objectstore.ObjectInfo, len(stored))
|
||||
for _, object := range stored {
|
||||
objectByKey[object.Key] = object
|
||||
}
|
||||
|
||||
// Objects with no metadata row: candidate orphans, unless still fresh.
|
||||
for _, object := range stored {
|
||||
if _, known := dbByKey[object.Key]; known {
|
||||
continue
|
||||
}
|
||||
age := ageSeconds(now, object.LastModified)
|
||||
if object.LastModified.IsZero() || age < int64(grace.Seconds()) {
|
||||
result.Findings.ProtectedObjects = append(result.Findings.ProtectedObjects, item{
|
||||
ObjectKey: object.Key, AgeSeconds: age,
|
||||
})
|
||||
continue
|
||||
}
|
||||
result.Findings.OrphanObjects = append(result.Findings.OrphanObjects, item{
|
||||
ObjectKey: object.Key, AgeSeconds: age,
|
||||
})
|
||||
}
|
||||
|
||||
// Metadata rows: ready rows must have an object; pending rows are internal
|
||||
// upload intents and are cleaned only after the grace period.
|
||||
for _, row := range rows {
|
||||
_, exists := objectByKey[row.ObjectKey]
|
||||
age := ageSeconds(now, row.UpdatedAt)
|
||||
switch row.Status {
|
||||
case "ready":
|
||||
if exists {
|
||||
result.Findings.OK++
|
||||
} else {
|
||||
result.Findings.MissingObjects = append(result.Findings.MissingObjects, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status, AgeSeconds: age,
|
||||
})
|
||||
}
|
||||
case "pending":
|
||||
if age >= int64(grace.Seconds()) {
|
||||
result.Findings.StalePending = append(result.Findings.StalePending, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
|
||||
AgeSeconds: age, ObjectPresent: exists,
|
||||
})
|
||||
} else {
|
||||
result.Findings.ProtectedPending = append(result.Findings.ProtectedPending, item{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
|
||||
AgeSeconds: age, ObjectPresent: exists,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
sortFindings(&result.Findings)
|
||||
|
||||
if *apply {
|
||||
applyActions(ctx, repository, objects, result.Findings.OrphanObjects, result.Findings.StalePending, *grace, &result.Actions)
|
||||
} else {
|
||||
for _, orphan := range result.Findings.OrphanObjects {
|
||||
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, orphan.ObjectKey)
|
||||
}
|
||||
for _, pending := range result.Findings.StalePending {
|
||||
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, pending.ObjectKey)
|
||||
}
|
||||
}
|
||||
for _, missing := range result.Findings.MissingObjects {
|
||||
result.Actions.UnresolvedMissing = append(result.Actions.UnresolvedMissing, missing.ID)
|
||||
}
|
||||
result.Timing.TotalMS = time.Since(started).Milliseconds()
|
||||
|
||||
encoded, err := json.MarshalIndent(result, "", " ")
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: encode report failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(string(encoded))
|
||||
if *output != "" {
|
||||
if err := os.WriteFile(*output, append(encoded, '\n'), 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "reconciler: write report failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
if len(result.Actions.Errors) > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// applyActions performs the two safe mutations. Broken ready metadata is never
|
||||
// deleted: automatic deletion would destroy the only record of a user's file
|
||||
// and could hide data loss. Each mutation re-reads the database first.
|
||||
func applyActions(ctx context.Context, repository *store.Store, objects *objectstore.Store, orphans, stale []item, grace time.Duration, result *actions) {
|
||||
for _, orphan := range orphans {
|
||||
stillReferenced, err := repository.AttachmentByObjectKey(ctx, orphan.ObjectKey)
|
||||
if err != nil {
|
||||
result.Errors = append(result.Errors, "recheck "+orphan.ObjectKey+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if stillReferenced {
|
||||
result.Skipped = append(result.Skipped, orphan.ObjectKey)
|
||||
continue
|
||||
}
|
||||
if err := objects.Remove(ctx, orphan.ObjectKey); err != nil {
|
||||
result.Errors = append(result.Errors, "delete "+orphan.ObjectKey+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
result.DeletedObjects = append(result.DeletedObjects, orphan.ObjectKey)
|
||||
}
|
||||
for _, pending := range stale {
|
||||
status, key, updatedAt, err := repository.AttachmentState(ctx, pending.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
result.Errors = append(result.Errors, "recheck "+pending.ID+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if status != "pending" {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
if time.Since(updatedAt) < grace {
|
||||
// Defensive: the snapshot said stale, but the row is fresh now
|
||||
// (a retried upload may have updated it). Never delete it.
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
// Delete the intent row first, then the object. The reverse order has
|
||||
// a race: a concurrent MarkAttachmentReady could promote the row
|
||||
// between Remove and DELETE, leaving a ready row whose bytes are gone.
|
||||
// With this order a crash after the row delete leaves an orphan object
|
||||
// that the next run removes after the grace period.
|
||||
deleted, err := repository.DeleteAttachmentIfPending(ctx, pending.ID)
|
||||
if err != nil {
|
||||
result.Errors = append(result.Errors, "delete row "+pending.ID+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
if !deleted {
|
||||
result.Skipped = append(result.Skipped, pending.ObjectKey)
|
||||
continue
|
||||
}
|
||||
result.DeletedPendingRows = append(result.DeletedPendingRows, pending.ID)
|
||||
if !pending.ObjectPresent {
|
||||
continue
|
||||
}
|
||||
if err := objects.Remove(ctx, key); err != nil {
|
||||
result.Errors = append(result.Errors, "delete orphaned object after row "+key+": "+err.Error())
|
||||
continue
|
||||
}
|
||||
result.DeletedObjects = append(result.DeletedObjects, key)
|
||||
}
|
||||
}
|
||||
|
||||
func ageSeconds(now, then time.Time) int64 {
|
||||
if then.IsZero() {
|
||||
return -1
|
||||
}
|
||||
age := now.Sub(then)
|
||||
if age < 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(age.Seconds())
|
||||
}
|
||||
|
||||
func sortFindings(value *findings) {
|
||||
sort.Slice(value.OrphanObjects, func(i, j int) bool { return value.OrphanObjects[i].ObjectKey < value.OrphanObjects[j].ObjectKey })
|
||||
sort.Slice(value.ProtectedObjects, func(i, j int) bool { return value.ProtectedObjects[i].ObjectKey < value.ProtectedObjects[j].ObjectKey })
|
||||
sort.Slice(value.MissingObjects, func(i, j int) bool { return value.MissingObjects[i].ObjectKey < value.MissingObjects[j].ObjectKey })
|
||||
sort.Slice(value.StalePending, func(i, j int) bool { return value.StalePending[i].ObjectKey < value.StalePending[j].ObjectKey })
|
||||
sort.Slice(value.ProtectedPending, func(i, j int) bool { return value.ProtectedPending[i].ObjectKey < value.ProtectedPending[j].ObjectKey })
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Command s3bootstrap creates the private attachment bucket idempotently and
|
||||
// proves that the configured administrative credentials can use it. It is a
|
||||
// one-shot compose service, separate from the API: API replicas never receive
|
||||
// the administrative credentials and cannot create buckets.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
)
|
||||
|
||||
func main() {
|
||||
endpoint := strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
|
||||
bucket := strings.TrimSpace(os.Getenv("S3_BUCKET"))
|
||||
region := strings.TrimSpace(os.Getenv("S3_REGION"))
|
||||
if region == "" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
accessKey := strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY"))
|
||||
secretKey := strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_KEY"))
|
||||
if endpoint == "" || bucket == "" || accessKey == "" || secretKey == "" {
|
||||
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_ENDPOINT, S3_BUCKET, S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_KEY are required")
|
||||
os.Exit(2)
|
||||
}
|
||||
timeout := 30 * time.Second
|
||||
if raw := strings.TrimSpace(os.Getenv("S3_TIMEOUT_SECONDS")); raw != "" {
|
||||
seconds, err := strconv.Atoi(raw)
|
||||
if err != nil || seconds < 5 || seconds > 120 {
|
||||
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_TIMEOUT_SECONDS must be an integer between 5 and 120")
|
||||
os.Exit(2)
|
||||
}
|
||||
timeout = time.Duration(seconds) * time.Second
|
||||
}
|
||||
store, err := objectstore.Open(objectstore.Config{
|
||||
Endpoint: endpoint,
|
||||
Region: region,
|
||||
Bucket: bucket,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
Timeout: timeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "s3bootstrap: configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
created, err := store.EnsureBucket(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "s3bootstrap: bucket creation failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := store.Probe(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "s3bootstrap: credential/bucket probe failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result := map[string]any{
|
||||
"bucket": bucket,
|
||||
"created": created,
|
||||
"verified": true,
|
||||
}
|
||||
encoded, _ := json.Marshal(result)
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Command s3ctl is a small operator/test helper for the private bucket. It is
|
||||
// not part of the HTTP API: it uses the same restricted API credentials as the
|
||||
// application and is used only to seed failure scenarios for the reconciler
|
||||
// and to prove that anonymous access and cross-bucket access are denied.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/config"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
)
|
||||
|
||||
func main() {
|
||||
op := flag.String("op", "", "put, get, stat, delete or list")
|
||||
key := flag.String("key", "", "object key")
|
||||
file := flag.String("file", "", "file to upload for -op put")
|
||||
contentType := flag.String("content-type", "application/octet-stream", "content type for -op put")
|
||||
prefix := flag.String("prefix", "", "prefix for -op list")
|
||||
bucketOverride := flag.String("bucket", "", "override the configured bucket (permission test)")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.LoadTool()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
bucket := cfg.S3Bucket
|
||||
if *bucketOverride != "" {
|
||||
bucket = *bucketOverride
|
||||
}
|
||||
store, err := objectstore.Open(objectstore.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
Region: cfg.S3Region,
|
||||
Bucket: bucket,
|
||||
AccessKey: cfg.S3AccessKey,
|
||||
SecretKey: cfg.S3SecretKey,
|
||||
Timeout: cfg.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
switch *op {
|
||||
case "put":
|
||||
if *key == "" || *file == "" {
|
||||
fail("-op put requires -key and -file")
|
||||
}
|
||||
handle, err := os.Open(*file)
|
||||
if err != nil {
|
||||
fail("cannot open -file: " + err.Error())
|
||||
}
|
||||
defer handle.Close()
|
||||
info, err := handle.Stat()
|
||||
if err != nil {
|
||||
fail("cannot stat -file: " + err.Error())
|
||||
}
|
||||
if err := store.Put(ctx, *key, handle, info.Size(), *contentType); err != nil {
|
||||
fail("put failed: " + err.Error())
|
||||
}
|
||||
print(map[string]any{"operation": "put", "key": *key, "size_bytes": info.Size()})
|
||||
case "delete":
|
||||
if *key == "" {
|
||||
fail("-op delete requires -key")
|
||||
}
|
||||
if err := store.Remove(ctx, *key); err != nil {
|
||||
fail("delete failed: " + err.Error())
|
||||
}
|
||||
print(map[string]any{"operation": "delete", "key": *key})
|
||||
case "stat":
|
||||
if *key == "" {
|
||||
fail("-op stat requires -key")
|
||||
}
|
||||
info, err := store.Stat(ctx, *key)
|
||||
if err != nil {
|
||||
fail("stat failed: " + err.Error())
|
||||
}
|
||||
print(map[string]any{"operation": "stat", "key": info.Key, "size_bytes": info.Size, "content_type": info.ContentType, "last_modified": info.LastModified.UTC().Format(time.RFC3339Nano)})
|
||||
case "list":
|
||||
items, err := store.List(ctx, *prefix)
|
||||
if err != nil {
|
||||
fail("list failed: " + err.Error())
|
||||
}
|
||||
keys := make([]map[string]any, 0, len(items))
|
||||
for _, item := range items {
|
||||
keys = append(keys, map[string]any{"key": item.Key, "size_bytes": item.Size, "last_modified": item.LastModified.UTC().Format(time.RFC3339Nano)})
|
||||
}
|
||||
print(map[string]any{"operation": "list", "bucket": bucket, "prefix": *prefix, "objects": keys})
|
||||
case "get":
|
||||
if *key == "" {
|
||||
fail("-op get requires -key")
|
||||
}
|
||||
body, info, err := store.Get(ctx, *key)
|
||||
if err != nil {
|
||||
fail("get failed: " + err.Error())
|
||||
}
|
||||
defer body.Close()
|
||||
buffer := make([]byte, 32*1024)
|
||||
written := int64(0)
|
||||
for {
|
||||
n, readErr := body.Read(buffer)
|
||||
if n > 0 {
|
||||
if _, err := os.Stdout.Write(buffer[:n]); err != nil {
|
||||
fail("write stdout failed")
|
||||
}
|
||||
written += int64(n)
|
||||
}
|
||||
if readErr != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "s3ctl: read %d of %d bytes\n", written, info.Size)
|
||||
default:
|
||||
fail("-op must be one of put, get, stat, delete or list")
|
||||
}
|
||||
}
|
||||
|
||||
func print(value any) {
|
||||
encoded, _ := json.Marshal(value)
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
|
||||
func fail(message string) {
|
||||
fmt.Fprintln(os.Stderr, "s3ctl:", message)
|
||||
os.Exit(1)
|
||||
}
|
||||
Reference in New Issue
Block a user