Implement lab 3 level 4 failover and idempotency

This commit is contained in:
2026-10-29 23:35:04 +03:00
parent 0ab3a341aa
commit a2cb1ad2ae
338 changed files with 37821 additions and 22 deletions
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Compare real WAITAOF waits on a new Redis/volume using current Compose settings."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import tempfile
import time
ROOT = Path(__file__).resolve().parents[2]
def command(args, timeout=60):
process = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
if process.returncode:
raise RuntimeError("diagnostic command failed: " + " ".join(args[:3]))
return process.stdout
def sources():
paths = [*ROOT.glob("internal/**/*.go"), *ROOT.glob("cmd/**/*.go"),
*ROOT.glob("db/**/*.sql"), ROOT / "compose.yaml", ROOT / "go.mod", ROOT / "go.sum"]
return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in paths if p.is_file() and not p.name.endswith("_test.go")}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=False)
project = "lab2-test-waitaof-" + secrets.token_hex(6)
container, volume = project + "-redis", project + "-data"
label = "com.docker.compose.project=" + project
before = sources()
summary = {"project": project, "status": "FAIL", "source_before": before}
volume_created = False
try:
# Read the Compose model in memory. Only the Redis profile is saved;
# application environment/credentials never enter diagnostic artifacts.
config = json.loads(command(["docker", "compose", "--project-directory", str(ROOT),
"-p", project, "-f", str(ROOT / "compose.yaml"),
"config", "--format", "json"]))
redis = config["services"]["redis"]
profile = {"image": redis["image"], "command": redis["command"]}
if not isinstance(profile["command"], list):
raise RuntimeError("Redis command must be an argv list")
image = json.loads(command(["docker", "image", "inspect", profile["image"]]))[0]
summary.update(redis_profile=profile, image_id=image["Id"], image_digests=image.get("RepoDigests", []))
# Run the inspected image ID, so a mutable tag cannot change mid-run.
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
port = reservation.getsockname()[1]
command(["docker", "volume", "create", "--label", label, volume])
volume_created = True
command(["docker", "run", "-d", "--name", container, "--label", label,
"-p", f"127.0.0.1:{port}:6379", "--mount", f"type=volume,src={volume},dst=/data",
image["Id"], *profile["command"]])
for _ in range(60):
ping = subprocess.run(["docker", "exec", container, "redis-cli", "ping"],
capture_output=True, text=True, timeout=5)
if ping.returncode == 0 and ping.stdout.strip() == "PONG":
break
time.sleep(.2)
else:
raise RuntimeError("test Redis is not ready")
with tempfile.TemporaryDirectory(prefix=project + "-") as directory:
binary = Path(directory) / "compare-waitaof"
command(["go", "build", "-o", str(binary), "./student-tests/diagnostics/waitaof"], timeout=120)
env = dict(os.environ, WAITAOF_TEST_REDIS_ADDR=f"127.0.0.1:{port}")
process = subprocess.Popen([str(binary), "-output", str(output)], cwd=ROOT, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
# Per-command deadlines bound the client; 36 sequential samples.
try:
with (output / "client.log").open("w") as log:
for line in process.stdout:
log.write(line)
log.flush()
print(line, end="", flush=True)
code = process.wait(timeout=10)
finally:
if process.poll() is None:
process.terminate()
process.wait(timeout=10)
summary["client_exit"] = code
summary["status"] = "COMPLETE" if code == 0 else "FAIL"
except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as error:
summary["failure"] = str(error)
finally:
after = sources()
summary["source_after"] = after
summary["production_source_changes"] = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))
inspected = subprocess.run(["docker", "inspect", container], capture_output=True, text=True)
if inspected.returncode == 0:
owned = json.loads(inspected.stdout)[0]["Config"]["Labels"].get("com.docker.compose.project") == project
summary["container_cleanup"] = owned and subprocess.run(
["docker", "rm", "-f", container], capture_output=True).returncode == 0
else:
summary["container_cleanup"] = True
summary["volume_cleanup"] = not volume_created or subprocess.run(
["docker", "volume", "rm", volume], capture_output=True).returncode == 0
if not summary["container_cleanup"] or not summary["volume_cleanup"]:
summary["status"] = "FAIL"
(output / "runner-summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
print(summary["status"] + ": " + str(output), flush=True)
return 0 if summary["status"] == "COMPLETE" else 1
if __name__ == "__main__":
raise SystemExit(main())
+206
View File
@@ -0,0 +1,206 @@
// Standalone experiment; production constructors and timeouts are never used.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
func save(path string, v any) error {
b, e := json.MarshalIndent(v, "", " ")
if e != nil {
return e
}
return os.WriteFile(path, append(b, '\n'), 0600)
}
func snapshot(c *redis.Client, out, phase string) (map[string]any, error) {
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
settings := map[string]string{}
for _, pattern := range []string{"append*", "*aof*", "no-appendfsync-on-rewrite"} {
values, e := c.ConfigGet(ctx, pattern).Result()
if e != nil {
return nil, e
}
for k, v := range values {
settings[k] = v
}
}
info, e := c.Info(ctx, "persistence").Result()
if e != nil {
return nil, e
}
server, e := c.Info(ctx, "server").Result()
if e != nil {
return nil, e
}
if e = os.WriteFile(filepath.Join(out, "persistence-"+phase+".info"), []byte(info), 0600); e != nil {
return nil, e
}
if e = os.WriteFile(filepath.Join(out, "server-"+phase+".info"), []byte(server), 0600); e != nil {
return nil, e
}
s := map[string]any{"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "aof_settings": settings, "info_persistence": info, "info_server": server}
return s, save(filepath.Join(out, "snapshot-"+phase+".json"), s)
}
func measure(c *redis.Client, number, round, budget, pause int) map[string]any {
key := "waitaof-probe:" + uuid.NewString()
errors := map[string]string{}
s := map[string]any{"number": number, "round": round, "waitaof_timeout_ms": budget, "scheduled_pause_ms": pause, "synthetic_key": key, "errors": errors, "local_fsynced": nil, "replicas_fsynced": nil}
// Conn pins all commands to one physical connection. IDs before/after also
// detect reconnects; such samples are invalid rather than acknowledged.
conn := c.Conn()
defer conn.Close()
initCtx, initCancel := context.WithTimeout(context.Background(), 12*time.Second)
before, e := conn.ClientID(initCtx).Result()
initCancel()
if e != nil {
errors["client_id_before"] = e.Error()
return s
}
s["client_id_before"] = before
paused := time.Now()
time.Sleep(time.Duration(pause) * time.Millisecond)
s["actual_pause_ms"] = ms(time.Since(paused))
// The pause does not consume any of the command deadline.
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
start := time.Now()
s["write_started_at_utc"] = start.UTC().Format(time.RFC3339Nano)
e = conn.Set(ctx, key, "synthetic-waitaof-value", time.Minute).Err()
s["set_ms"] = ms(time.Since(start))
if e != nil {
errors["set"] = e.Error()
} else {
t := time.Now()
deleted, delErr := conn.Del(ctx, key).Result()
s["del_ms"] = ms(time.Since(t))
s["deleted"] = deleted
if delErr != nil {
errors["del"] = delErr.Error()
} else {
if deleted != 1 {
errors["deleted_count"] = "expected exactly one newly written key"
}
t = time.Now()
reply, waitErr := conn.Do(ctx, "WAITAOF", 1, 0, budget).Slice()
s["waitaof_ms"] = ms(time.Since(t))
if waitErr != nil {
errors["waitaof"] = waitErr.Error()
} else if len(reply) != 2 {
errors["reply"] = "expected two counters"
} else {
local, okLocal := reply[0].(int64)
replicas, okReplicas := reply[1].(int64)
if !okLocal || !okReplicas {
errors["reply"] = "expected integer counters"
} else {
s["local_fsynced"] = local
s["replicas_fsynced"] = replicas
}
}
}
}
s["write_delete_wait_ms"] = ms(time.Since(start))
after, e := conn.ClientID(ctx).Result()
s["client_id_after"] = after
if e != nil {
errors["client_id_after"] = e.Error()
}
if before != after {
errors["pinned_connection"] = "connection ID changed"
}
exists, e := conn.Exists(ctx, key).Result()
s["exists_after"] = exists
if e != nil {
errors["exists"] = e.Error()
}
if exists != 0 {
errors["key_remains"] = "synthetic key was not deleted"
cleanup, done := context.WithTimeout(context.Background(), 8*time.Second)
defer done()
if e = conn.Del(cleanup, key).Err(); e != nil {
errors["cleanup"] = e.Error()
}
}
return s
}
func run(out string) error {
addr := os.Getenv("WAITAOF_TEST_REDIS_ADDR")
if addr == "" {
return fmt.Errorf("set WAITAOF_TEST_REDIS_ADDR for a dedicated test Redis")
}
c := redis.NewClient(&redis.Options{Addr: addr, DialTimeout: 8 * time.Second, ReadTimeout: 8 * time.Second, WriteTimeout: 8 * time.Second, PoolTimeout: 8 * time.Second, ContextTimeoutEnabled: true, MaxRetries: -1, PoolSize: 1})
defer c.Close()
before, e := snapshot(c, out, "before")
if e != nil {
return e
}
file, e := os.OpenFile(filepath.Join(out, "samples.jsonl"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if e != nil {
return e
}
defer file.Close()
encoder := json.NewEncoder(file)
pauses := []int{0, 137, 359, 613, 887, 1109}
samples := []map[string]any{}
invalid := 0
for round := 1; round <= 3; round++ {
for i := range pauses {
pause := pauses[(i+round-1)%len(pauses)]
budgets := []int{1000, 3000}
if (round+i)%2 == 0 {
budgets = []int{3000, 1000}
}
for _, budget := range budgets {
s := measure(c, len(samples)+1, round, budget, pause)
samples = append(samples, s)
if len(s["errors"].(map[string]string)) > 0 {
invalid++
}
if e = encoder.Encode(s); e != nil {
return e
}
if e = file.Sync(); e != nil {
return e
}
fmt.Printf("sample=%d round=%d timeout_ms=%d pause_ms=%d wait_ms=%v local=%v replicas=%v errors=%d\n", len(samples), round, budget, pause, s["waitaof_ms"], s["local_fsynced"], s["replicas_fsynced"], len(s["errors"].(map[string]string)))
}
}
}
after, e := snapshot(c, out, "after")
if e != nil {
return e
}
result := map[string]any{"complete": true, "invalid_samples": invalid, "settings": map[string]any{"network_timeout_ms": 8000, "command_deadline_ms": 12000, "retries": 0, "pool_size": 1, "repetitions_per_pause_per_timeout": 3, "scheduled_pauses_ms": pauses, "ordering": "alternate timeout order and rotate pauses each round"}, "before": before, "after": after, "samples": samples}
if e = save(filepath.Join(out, "experiment.json"), result); e != nil {
return e
}
if invalid > 0 {
return fmt.Errorf("%d invalid samples; inspect errors in raw results", invalid)
}
return nil
}
func main() {
out := flag.String("output", "", "existing dedicated experiment directory")
flag.Parse()
if *out == "" {
fmt.Fprintln(os.Stderr, "-output is required")
os.Exit(2)
}
if e := run(*out); e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
}