diff --git a/.gitignore b/.gitignore index f78be92..1f85df1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ bin/ .agents/ .codex/ ucloud-sandbox-cli +.idea diff --git a/CLAUDE.md b/CLAUDE.md index f02686d..3ed58e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,12 +46,20 @@ make test ## 项目结构 ### `cmd/` -所有CLI命令的实现都放在此目录。每个命令通过 `NewCmd()` 函数返回 `*cobra.Command`。 +所有CLI命令的实现都放在此目录,每个命令组一个子包(如 `cmd/sandbox/`、`cmd/auth/`)。 + +**命令组:** 子包导出 `Command() *cobra.Command`,返回命令组并注册其下的子命令;顶层命令组在 `main.go` 中注册。 + +**子命令:** 每个子命令是一个实现了 `cmd.Operation` 接口的 `Operation` 结构体(未导出),flag 绑定到结构体字段: +- `Command() *cobra.Command`:定义 `Use`、`Short`、`Args` 和 flags +- `Run(ctx cmd.OperationContext) error`:执行命令,通过 `ctx.Client` 调用 SDK + +注册时用 `cmd.Build(&xxxOperation{})` 包装,它会加载配置并创建 SDK client;只读写本地配置、不需要 client 的命令(如 `login`、`update`)用 `cmd.BuildLocal`。 **新增命令时需要:** -1. 参考现有命令的实现方式(如 `login.go`、`logout.go`、`region.go`) +1. 参考现有命令的实现方式(如 `cmd/sandbox/kill.go`、`cmd/auth/region.go`) 2. 遵循相同的代码风格和错误处理模式 -3. 命令函数命名规范:`NewCmd()` +3. 命名规范:命令组为 `Command()`,子命令为 `Operation` ### `internal/` 存放CLI使用的公用包 diff --git a/cmd/benchmark/benchmark.go b/cmd/benchmark/benchmark.go new file mode 100644 index 0000000..2131ff3 --- /dev/null +++ b/cmd/benchmark/benchmark.go @@ -0,0 +1,20 @@ +package benchmark + +import ( + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" +) + +// Command returns the root benchmark command group. +func Command() *cobra.Command { + c := &cobra.Command{ + Use: "benchmark", + Aliases: []string{"bench"}, + Short: "Benchmark the sandbox service", + } + c.AddCommand(cmd.Build(&createOperation{})) + c.AddCommand(cmd.Build(&healthOperation{})) + c.AddCommand(cmd.Build(&lifecycleOperation{})) + c.AddCommand(cmd.Build(&snapshotOperation{})) + return c +} diff --git a/cmd/benchmark/benchmark_test.go b/cmd/benchmark/benchmark_test.go new file mode 100644 index 0000000..01f66fd --- /dev/null +++ b/cmd/benchmark/benchmark_test.go @@ -0,0 +1,614 @@ +package benchmark + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/api" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/client" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox" +) + +func parseLifecycle(t *testing.T, args ...string) *lifecycleOperation { + t.Helper() + op := &lifecycleOperation{} + c := op.Command() + require.NoError(t, c.ParseFlags(args)) + return op +} + +func TestLifecycleDefaults(t *testing.T) { + op := parseLifecycle(t) + + assert.Equal(t, "system/base", op.template) + assert.Equal(t, 10, op.count) + assert.Equal(t, 1, op.concurrency) + assert.Equal(t, "echo ok", op.command) + assert.EqualValues(t, 300, op.timeout) + assert.Equal(t, "pretty", op.format) + assert.NoError(t, op.validate()) +} + +func TestLifecycleValidate(t *testing.T) { + tests := []struct { + name string + args []string + err string + }{ + {"zero count", []string{"-n", "0"}, "--count"}, + {"zero concurrency", []string{"-c", "0"}, "--concurrency"}, + {"zero timeout", []string{"--timeout", "0"}, "--timeout"}, + {"empty command", []string{"--cmd", ""}, "--cmd"}, + {"bad format", []string{"-f", "yaml"}, "--format"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := parseLifecycle(t, tt.args...).validate() + require.Error(t, err) + assert.Contains(t, err.Error(), tt.err) + }) + } + + assert.NoError(t, parseLifecycle(t, "--cmd", "", "--skip-exec").validate(), + "an empty command is fine when exec is skipped") + assert.NoError(t, parseLifecycle(t, "-t", "my-tpl", "-n", "50", "-c", "8", "-f", "json").validate()) +} + +func sampleReport() benchmark.Report { + stats := benchmark.Stats{ + Count: 2, + Avg: 1500 * time.Millisecond, + Min: time.Second, + P50: time.Second, + P95: 2 * time.Second, + P99: 2 * time.Second, + Max: 2 * time.Second, + } + return benchmark.Report{ + Requested: 3, + Started: 3, + Succeeded: 2, + Failed: 1, + Elapsed: 4 * time.Second, + Phases: []benchmark.PhaseReport{ + { + Phase: benchmark.PhaseCreate, + Stats: stats, + Connect: benchmark.Stats{Count: 2, Avg: 100 * time.Millisecond, Min: 0, P50: 0, P95: 200 * time.Millisecond, P99: 200 * time.Millisecond, Max: 200 * time.Millisecond}, + Service: benchmark.Stats{Count: 2, Avg: 1400 * time.Millisecond, Min: time.Second, P50: time.Second, P95: 1800 * time.Millisecond, P99: 1800 * time.Millisecond, Max: 1800 * time.Millisecond}, + }, + {Phase: benchmark.PhaseExec, Failed: 1}, + }, + Errors: []benchmark.ErrorCount{ + {Phase: benchmark.PhaseExec, Message: "exit status 1", Count: 1}, + }, + Leaked: []string{"sbx-1"}, + } +} + +func TestLifecycleViewJSON(t *testing.T) { + v := newRunView("run-1", "system/base", 2, 300, sampleReport()) + + data, err := json.Marshal(v) + require.NoError(t, err) + + var decoded map[string]any + require.NoError(t, json.Unmarshal(data, &decoded)) + + assert.Equal(t, "run-1", decoded["run_id"]) + assert.InDelta(t, 4000, decoded["elapsed_ms"], 1e-9) + assert.InDelta(t, 0.5, decoded["rate_per_sec"], 1e-9) + + phases := decoded["phases"].([]any) + require.Len(t, phases, 2) + create := phases[0].(map[string]any) + assert.Equal(t, "create", create["phase"]) + assert.InDelta(t, 1500, create["avg_ms"], 1e-9) + assert.InDelta(t, 2000, create["p99_ms"], 1e-9) + assert.InDelta(t, 200, create["connect"].(map[string]any)["p99_ms"], 1e-9) + assert.InDelta(t, 1400, create["service"].(map[string]any)["avg_ms"], 1e-9) + + assert.Equal(t, []any{"sbx-1"}, decoded["leaked"]) +} + +func TestLifecycleViewJSONEmptyListsAreArrays(t *testing.T) { + v := newRunView("run-1", "system/base", 1, 300, benchmark.Report{}) + + data, err := json.Marshal(v) + require.NoError(t, err) + + assert.Contains(t, string(data), `"errors":[]`) + assert.Contains(t, string(data), `"leaked":[]`) + assert.Contains(t, string(data), `"iterations":[]`) +} + +func TestRunViewJSONIterations(t *testing.T) { + r := sampleReport() + r.Iterations = []benchmark.IterationResult{ + { + Seq: 1, + Start: 1500 * time.Microsecond, + SandboxID: "sbx-1", + Phases: []benchmark.PhaseResult{ + {Phase: benchmark.PhaseCreate, Duration: time.Second, Connect: 200 * time.Millisecond}, + {Phase: benchmark.PhaseExec, Err: errors.New("exit status 1:\n sbx-1 said no")}, + {Phase: benchmark.PhaseKill, Duration: 50 * time.Millisecond}, + }, + Leaked: []string{"sbx-1"}, + }, + { + Seq: 2, + Start: 3 * time.Millisecond, + Phases: []benchmark.PhaseResult{{Phase: benchmark.PhaseCreate, Err: errors.New("quota exceeded")}}, + }, + } + + data, err := json.Marshal(newRunView("run-1", "system/base", 2, 300, r)) + require.NoError(t, err) + + var decoded struct { + Iterations []map[string]any `json:"iterations"` + } + require.NoError(t, json.Unmarshal(data, &decoded)) + require.Len(t, decoded.Iterations, 2) + + first := decoded.Iterations[0] + assert.InDelta(t, 1, first["seq"], 0) + assert.Equal(t, "sbx-1", first["sandbox_id"]) + assert.InDelta(t, 1.5, first["start_offset_ms"], 1e-9) + assert.Equal(t, false, first["succeeded"]) + assert.Equal(t, []any{"sbx-1"}, first["leaked"]) + assert.Equal(t, []any{ + map[string]any{"phase": "create", "duration_ms": 1000.0, "connect_ms": 200.0}, + // The sandbox ID is kept, unlike in the grouped errors. + map[string]any{"phase": "exec", "error": "exit status 1: sbx-1 said no"}, + // A zero connect time is still written. + map[string]any{"phase": "kill", "duration_ms": 50.0, "connect_ms": 0.0}, + }, first["phases"]) + + second := decoded.Iterations[1] + assert.Equal(t, "", second["sandbox_id"], "a failed create has no sandbox") + assert.Equal(t, []any{}, second["leaked"]) + assert.Equal(t, []any{map[string]any{"phase": "create", "error": "quota exceeded"}}, second["phases"]) +} + +func TestRunViewPrettyOmitsIterations(t *testing.T) { + r := sampleReport() + r.Iterations = []benchmark.IterationResult{{Seq: 1, SandboxID: "sbx-iteration"}} + + var b strings.Builder + require.NoError(t, newRunView("run-1", "system/base", 2, 300, r).writePretty(&b)) + + assert.NotContains(t, b.String(), "sbx-iteration") +} + +func TestLifecycleViewPretty(t *testing.T) { + v := newRunView("run-1", "system/base", 2, 300, sampleReport()) + v.breakdown = true + + var b strings.Builder + require.NoError(t, v.writePretty(&b)) + out := b.String() + + assert.Contains(t, out, "Benchmark run-1 completed: template system/base, concurrency 2") + assert.Contains(t, out, "Iterations: 3/3 started, 2 succeeded, 1 failed") + assert.Contains(t, out, "Elapsed: 4s, rate: 0.50 sandbox/s") + assert.Contains(t, out, "Latency per phase, split into connection setup (connect) and service time (service):\n+") + assert.Contains(t, out, "| create | 2 | 0 | 1.5s | 1s | 1s | 2s | 2s | 2s |") + assert.Contains(t, out, "| connect | - | - | 100ms | 0s | 0s | 200ms | 200ms | 200ms |") + assert.Contains(t, out, "| service | - | - | 1.4s | 1s | 1s | 1.8s | 1.8s | 1.8s |") + assert.NotContains(t, out, "Page:") + + // A phase without a single success shows no latencies and no breakdown. + assert.Contains(t, out, "| exec | 0 | 1 | - | - | - | - | - | - |\n+") + + assert.Contains(t, out, "Errors:") + assert.Contains(t, out, "exit status 1") + assert.Contains(t, out, "sandbox kill --all -m benchmark=run-1") +} + +func TestRunViewShowsServiceTimeByDefault(t *testing.T) { + var b strings.Builder + require.NoError(t, newRunView("run-1", "system/base", 2, 300, sampleReport()).writePretty(&b)) + out := b.String() + + // The create row carries the service time (1.4s avg), not the full + // latency (1.5s), and nothing is broken out under it. + assert.Contains(t, out, "| create | 2 | 0 | 1.4s | 1s | 1s | 1.8s | 1.8s | 1.8s |") + assert.Contains(t, out, "| exec | 0 | 1 | - | - | - | - | - | - |") + assert.Contains(t, out, "Service time per phase, excluding connection setup (DNS, dial, TLS); --breakdown shows the full latency:\n+") + assert.NotContains(t, out, "| connect") + assert.NotContains(t, out, "| service") +} + +func TestOutputFlag(t *testing.T) { + op := parseLifecycle(t) + assert.Empty(t, op.output, "no report file by default") + + op = parseLifecycle(t, "-o", "/tmp/report.json") + assert.Equal(t, "/tmp/report.json", op.output) + assert.NoError(t, op.validate(), "the path is checked when it is written") + + assert.Equal(t, "/tmp/report.json", parseLifecycle(t, "--output", "/tmp/report.json").output) +} + +func TestReportInterruptionAnnounces(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + var b strings.Builder + stopped := false + reportInterruption(ctx, make(chan struct{}), func() { stopped = true }, &b, "cleanup-cmd") + + assert.True(t, stopped, "the default signal handling is restored, so a second Ctrl+C quits") + assert.Contains(t, b.String(), "Interrupted: waiting for in-flight iterations to finish") + assert.Contains(t, b.String(), "cleanup-cmd") +} + +func TestReportInterruptionSilentWhenRunFinished(t *testing.T) { + // Both channels are ready, as when a run finishes in the instant its + // context is cancelled: the run was not interrupted. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + finished := make(chan struct{}) + close(finished) + + var b strings.Builder + stopped := false + reportInterruption(ctx, finished, func() { stopped = true }, &b, "cleanup-cmd") + + assert.Empty(t, b.String()) + assert.False(t, stopped) +} + +func TestReportInterruptionSilentWithoutCancellation(t *testing.T) { + finished := make(chan struct{}) + close(finished) + + var b strings.Builder + reportInterruption(context.Background(), finished, func() {}, &b, "cleanup-cmd") + + assert.Empty(t, b.String()) +} + +func TestCheckReportFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "report.json") + require.NoError(t, checkReportFile(path)) + _, err := os.Stat(path) + require.NoError(t, err, "the file is created up front") + + assert.NoError(t, checkReportFile(path), "an existing file is fine") + + err = checkReportFile(filepath.Join(t.TempDir(), "missing", "report.json")) + require.Error(t, err) + assert.Contains(t, err.Error(), "report file") +} + +func TestRunViewWritesJSONFile(t *testing.T) { + r := sampleReport() + r.Iterations = []benchmark.IterationResult{{Seq: 1, SandboxID: "sbx-1"}} + path := filepath.Join(t.TempDir(), "report.json") + + require.NoError(t, newRunView("run-1", "system/base", 2, 300, r).writeJSONFile(path)) + + data, err := os.ReadFile(path) + require.NoError(t, err) + + var decoded map[string]any + require.NoError(t, json.Unmarshal(data, &decoded), "the file holds one JSON document") + assert.Equal(t, "run-1", decoded["run_id"]) + phases := decoded["phases"].([]any) + require.Len(t, phases, 2) + assert.InDelta(t, 1500, phases[0].(map[string]any)["avg_ms"], 1e-9, "the summary is in the file too") + require.Len(t, decoded["iterations"].([]any), 1) + + // The document is the one --format json prints. + var stdout []byte + v := newRunView("run-1", "system/base", 2, 300, r) + stdout, err = json.MarshalIndent(v, "", " ") + require.NoError(t, err) + assert.JSONEq(t, string(stdout), string(data)) +} + +func TestRunViewWriteJSONFileReportsBadPath(t *testing.T) { + path := filepath.Join(t.TempDir(), "missing", "report.json") + err := newRunView("run-1", "system/base", 1, 300, benchmark.Report{}).writeJSONFile(path) + require.Error(t, err) + assert.Contains(t, err.Error(), "write report") +} + +func TestBreakdownFlag(t *testing.T) { + op := parseLifecycle(t) + assert.False(t, op.breakdown, "off by default") + + op = parseLifecycle(t, "--breakdown") + assert.True(t, op.breakdown) +} + +func TestLifecycleViewPrettyInterrupted(t *testing.T) { + r := sampleReport() + r.Interrupted = true + r.Errors, r.Leaked = nil, nil + + var b strings.Builder + require.NoError(t, newRunView("run-1", "system/base", 1, 300, r).writePretty(&b)) + out := b.String() + + assert.Contains(t, out, "Benchmark run-1 interrupted") + assert.NotContains(t, out, "Errors:") + assert.NotContains(t, out, "could not be killed") +} + +func TestWithoutRetriesFailsRateLimitedRequestAtOnce(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Header().Set("Retry-After", "0") + w.WriteHeader(http.StatusTooManyRequests) + })) + defer srv.Close() + + newClient := func(modifiers ...func(*client.Options)) *client.Client { + opts := client.Options{APIKey: "test-key", APIURL: srv.URL} + for _, modify := range modifiers { + modify(&opts) + } + c, err := client.New(opts) + require.NoError(t, err) + return c + } + + // The SDK's default retries the 429, which the benchmark must not time. + _, err := newClient().Sandboxes().Kill(context.Background(), "sbx") + require.Error(t, err) + require.Greater(t, hits.Load(), int32(1), "the SDK retries a 429 by default") + + hits.Store(0) + _, err = newClient(withoutRetries).Sandboxes().Kill(context.Background(), "sbx") + require.Error(t, err) + assert.EqualValues(t, 1, hits.Load()) +} + +// TestLifecycleTracesSDKConnections runs the benchmark against a fake control +// plane through the real SDK, checking that the requests it makes carry the +// benchmark's context, so their connection setup is measured. +func TestLifecycleTracesSDKConnections(t *testing.T) { + var createBody atomic.Pointer[api.NewSandbox] + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + var req api.NewSandbox + _ = json.NewDecoder(r.Body).Decode(&req) + createBody.Store(&req) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"sandboxID":"sbx-1","templateID":"tpl","clientID":"c","envdVersion":"0.2.0"}`)) + case http.MethodDelete: + w.WriteHeader(http.StatusNoContent) + } + })) + defer srv.Close() + + sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) + require.NoError(t, err) + + op := parseLifecycle(t, "--skip-exec") + report := benchmark.Run(context.Background(), newCreator(sdk.Sandboxes(), "run-1", op.template, op.timeout), + benchmark.Options[*benchSandbox]{Count: 1, Concurrency: 1}) + + require.Equal(t, 1, report.Succeeded, "errors: %v", report.Errors) + for _, p := range report.Phases { + assert.Equal(t, 1, p.Connect.Count, p.Phase) + } + // The first request dials a fresh connection, which takes measurable time. + assert.Positive(t, report.Phases[0].Connect.Max) + + // Every sandbox is tagged with the run and marked as opened by the + // benchmark. + req := createBody.Load() + require.NotNil(t, req) + require.NotNil(t, req.Metadata) + assert.Equal(t, "run-1", (*req.Metadata)[runIDMetadataKey]) + assert.Equal(t, "sandbox-bench", (*req.Metadata)[sandbox.ManageByMetadataKey]) +} + +func TestCreateFlags(t *testing.T) { + op := &createOperation{} + c := op.Command() + + require.NoError(t, c.ParseFlags([]string{"-t", "my-tpl", "-n", "50", "-c", "8", "--timeout", "600"})) + assert.Equal(t, "my-tpl", op.template) + assert.Equal(t, 50, op.count) + assert.Equal(t, 8, op.concurrency) + assert.EqualValues(t, 600, op.timeout) + assert.NoError(t, op.validate()) + + assert.Error(t, (&createOperation{}).Command().ParseFlags([]string{"--cmd", "ls"}), + "create runs no command in its sandboxes") +} + +func TestCreateDefaultTimeoutIsFiveMinutes(t *testing.T) { + op := &createOperation{} + require.NoError(t, op.Command().ParseFlags(nil)) + assert.EqualValues(t, 300, op.timeout) +} + +func TestRunViewLeftRunning(t *testing.T) { + r := sampleReport() + r.Leaked = nil + v := newRunView("run-1", "system/base", 1, 300, r) + v.LeftRunning = 2 + + var b strings.Builder + require.NoError(t, v.writePretty(&b)) + out := b.String() + assert.Contains(t, out, "2 sandbox(es) left running, reclaimed after their 5m0s timeout.") + assert.Contains(t, out, "sandbox kill --all -m benchmark=run-1") + + data, err := json.Marshal(v) + require.NoError(t, err) + assert.Contains(t, string(data), `"left_running":2`) + assert.Contains(t, string(data), `"sandbox_timeout_sec":300`) +} + +// TestCreateOnlyKillsNothing runs a create-only benchmark against a fake +// control plane through the real SDK. +func TestCreateOnlyKillsNothing(t *testing.T) { + var creates, deletes atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + creates.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"sandboxID":"sbx-1","templateID":"tpl","clientID":"c","envdVersion":"0.2.0"}`)) + case http.MethodDelete: + deletes.Add(1) + w.WriteHeader(http.StatusNoContent) + } + })) + defer srv.Close() + + sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) + require.NoError(t, err) + + report := benchmark.Run(context.Background(), + newCreator(sdk.Sandboxes(), "run-1", "tpl", 300), + benchmark.Options[*benchSandbox]{Count: 3, Concurrency: 2, SkipKill: true}) + + require.Equal(t, 3, report.Succeeded, "errors: %v", report.Errors) + require.Len(t, report.Phases, 1) + assert.Equal(t, benchmark.PhaseCreate, report.Phases[0].Phase) + assert.EqualValues(t, 3, creates.Load()) + assert.Zero(t, deletes.Load()) +} + +// TestBenchSandboxKillNotFound pins the SDK contract benchSandbox.Kill relies +// on: only a 404 reads as not found, any other failure stays an error of its +// own. +func TestBenchSandboxKillNotFound(t *testing.T) { + tests := []struct { + name string + status int + notFound bool + wantErr bool + }{ + {"killed", http.StatusNoContent, false, false}, + {"not found", http.StatusNotFound, true, true}, + {"server error", http.StatusInternalServerError, false, true}, + {"conflict", http.StatusConflict, false, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"sandboxID":"sbx-1","templateID":"tpl","clientID":"c","envdVersion":"0.2.0"}`)) + return + } + w.WriteHeader(tt.status) + })) + defer srv.Close() + + sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) + require.NoError(t, err) + + sbx, err := newCreator(sdk.Sandboxes(), "run-1", "tpl", 300)(context.Background()) + require.NoError(t, err) + + err = sbx.Kill(context.Background()) + if !tt.wantErr { + assert.NoError(t, err) + return + } + require.Error(t, err) + assert.Equal(t, tt.notFound, errors.Is(err, benchmark.ErrSandboxNotFound)) + }) + } +} + +func TestNewRunID(t *testing.T) { + now := time.Date(2026, 11, 25, 11, 28, 42, 0, time.UTC) + + id := newRunID(now) + assert.Regexp(t, `^20261125-112842-[0-9a-f]{6}$`, id) + + seen := map[string]bool{} + for range 100 { + seen[newRunID(now)] = true + } + assert.Greater(t, len(seen), 90, "runs started in the same second get different IDs") +} + +func TestExitError(t *testing.T) { + assert.NoError(t, exitError(benchmark.Report{Requested: 3, Started: 3, Succeeded: 3})) + + err := exitError(benchmark.Report{Requested: 3, Started: 3, Succeeded: 2, Failed: 1}) + require.Error(t, err) + assert.Equal(t, "1 of 3 iteration(s) failed", err.Error()) + + err = exitError(benchmark.Report{Requested: 100, Started: 3, Succeeded: 3, Interrupted: true}) + require.Error(t, err, "an interrupted run is not a success, even with no failure") + assert.Equal(t, "interrupted: 3 of 100 iteration(s) started, 0 failed", err.Error()) +} + +func TestRunViewCleanupHint(t *testing.T) { + render := func(r benchmark.Report, leftRunning int) string { + v := newRunView("run-1", "system/base", 1, 300, r) + v.LeftRunning = leftRunning + var b strings.Builder + require.NoError(t, v.writePretty(&b)) + return b.String() + } + const cleanup = "ucloud-sandbox-cli sandbox kill --all -m benchmark=run-1" + + clean := benchmark.Report{Phases: []benchmark.PhaseReport{{Phase: benchmark.PhaseCreate}}} + assert.NotContains(t, render(clean, 0), cleanup, "nothing left behind, no hint") + + createFailed := benchmark.Report{Phases: []benchmark.PhaseReport{{Phase: benchmark.PhaseCreate, Failed: 2}}} + out := render(createFailed, 0) + assert.Contains(t, out, "2 create(s) failed; the service may still have started some of those sandboxes.") + assert.Contains(t, out, "Clean them up with: "+cleanup) + + out = render(clean, 3) + assert.Contains(t, out, "Kill them sooner with: "+cleanup) + + // Several reasons still print the command once. + r := sampleReport() + r.Phases[0].Failed = 1 + out = render(r, 2) + assert.Contains(t, out, "could not be killed") + assert.Contains(t, out, "Kill them with: ucloud-sandbox-cli sandbox kill sbx-1", "leaks are killed by ID, tagged or not") + assert.Contains(t, out, "1 create(s) failed") + assert.Contains(t, out, "2 sandbox(es) left running") + assert.Equal(t, 1, strings.Count(out, cleanup)) + assert.Contains(t, out, "Clean them up with: "+cleanup) +} + +func TestWriteHeader(t *testing.T) { + op := &runOptions{template: "system/base", count: 10, concurrency: 2} + + var b strings.Builder + op.writeHeader(&b, runSpec{name: "health"}, "20261125-225910-b2bbf0") + + assert.Equal(t, `Running health benchmark 20261125-225910-b2bbf0 + Template: system/base + Iterations: 10 (concurrency 2) + Sandbox tag: benchmark=20261125-225910-b2bbf0 + Cleanup: ucloud-sandbox-cli sandbox kill --all -m benchmark=20261125-225910-b2bbf0 + +`, b.String()) +} diff --git a/cmd/benchmark/create.go b/cmd/benchmark/create.go new file mode 100644 index 0000000..9ffda8c --- /dev/null +++ b/cmd/benchmark/create.go @@ -0,0 +1,36 @@ +package benchmark + +import ( + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" +) + +// createOperation times sandbox creation alone. The sandboxes are not killed: +// each lives until its timeout reclaims it, so the number running grows with +// every iteration. +type createOperation struct { + runOptions +} + +func (o *createOperation) Command() *cobra.Command { + c := &cobra.Command{ + Use: "create", + Short: "Measure sandbox create latency, leaving the sandboxes to time out", + Args: cobra.NoArgs, + } + + o.addFlags(c, 10, "Seconds each sandbox lives for before it is reclaimed; sandboxes are not killed") + + return c +} + +func (o *createOperation) Run(ctx cmd.OperationContext) error { + if err := o.validate(); err != nil { + return err + } + sdk, err := newClient(ctx.Config) + if err != nil { + return err + } + return o.run(ctx, sdk, runSpec{name: "create", skipKill: true}) +} diff --git a/cmd/benchmark/health.go b/cmd/benchmark/health.go new file mode 100644 index 0000000..f96cdd5 --- /dev/null +++ b/cmd/benchmark/health.go @@ -0,0 +1,498 @@ +package benchmark + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-cli/internal/config" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/api" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox/commands" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/transport" +) + +// Phases of a health check, besides create and kill. +const ( + phaseFilesystem benchmark.Phase = "filesystem" + phasePause benchmark.Phase = "pause" + phaseResume benchmark.Phase = "resume" +) + +// intranetURLTemplate builds the URL of a region's internal US3 (ufile) +// endpoint, which its sandboxes should reach over the intranet. +const intranetURLTemplate = "https://internal.s3-%s.ufileos.com/" + +// intranetRegionAliases lists the regions whose US3 endpoint is named after +// a region code of its own. +var intranetRegionAliases = map[string]string{ + "cn-sh": "cn-sh2", +} + +const ( + // probeTimeoutSec bounds one curl probe of an external address. + probeTimeoutSec = 10 + + // publicURLTimeout bounds how long the public URL check waits for the HTTP + // server in the sandbox to answer through the gateway. + publicURLTimeout = 30 * time.Second + + // publicURLPollInterval spaces the requests made while the server starts. + publicURLPollInterval = 500 * time.Millisecond +) + +// defaultInternetURL is the public URL checked by default: Apple's +// connectivity probe, served by a CDN close to every region, small and +// answering 200 without a redirect. +const defaultInternetURL = "https://www.apple.com/library/test/success.html" + +// healthChecks names the checks --skip and --only select from, in the order +// they run. "pause" covers both pausing and resuming, since a resume needs a +// paused sandbox. +var healthChecks = []string{"exec", "filesystem", "internet", "intranet", "public-url", "pause"} + +// healthOperation checks that the sandbox service works end to end: every +// sandbox is created, put through a series of checks and killed. +type healthOperation struct { + runOptions + + urls []string + intranetURL string + publicURLPort int + + skip []string + only []string +} + +func (o *healthOperation) Command() *cobra.Command { + c := &cobra.Command{ + Use: "health", + Short: "Check that sandboxes work: exec, files, internet, intranet, public URL, pause and resume", + Args: cobra.NoArgs, + } + + o.addFlags(c, 1, "Seconds each sandbox lives for, bounding any sandbox a failed kill leaves behind") + c.Flags().StringArrayVarP(&o.urls, "url", "", []string{defaultInternetURL}, + "Public URL the sandbox must reach; repeat to check several") + c.Flags().StringVarP(&o.intranetURL, "intranet-url", "", "", + "Intranet URL the sandbox must get an HTTP response from, whatever its status (default: the region's internal US3 endpoint)") + c.Flags().IntVarP(&o.publicURLPort, "public-url-port", "", 8000, + "Sandbox port the public URL check serves HTTP on") + + checks := strings.Join(healthChecks, ", ") + c.Flags().StringSliceVarP(&o.skip, "skip", "", nil, "Checks to leave out ("+checks+")") + c.Flags().StringSliceVarP(&o.only, "only", "", nil, "Checks to run, leaving out the rest ("+checks+")") + + return c +} + +func (o *healthOperation) validate() error { + if err := o.runOptions.validate(); err != nil { + return err + } + seen := make(map[string]bool, len(o.urls)) + for _, raw := range o.urls { + if !isHTTPURL(raw) { + return fmt.Errorf("invalid --url %q: must be an http or https URL", raw) + } + // Every URL is a phase of its own, named after it. + if seen[raw] { + return fmt.Errorf("duplicate --url %q", raw) + } + seen[raw] = true + } + if o.intranetURL != "" && !isHTTPURL(o.intranetURL) { + return fmt.Errorf("invalid --intranet-url %q: must be an http or https URL", o.intranetURL) + } + if o.publicURLPort < 1 || o.publicURLPort > 65535 { + return fmt.Errorf("invalid --public-url-port %d: must be between 1 and 65535", o.publicURLPort) + } + if len(o.skip) > 0 && len(o.only) > 0 { + return errors.New("--skip and --only cannot be used together") + } + for _, flag := range []struct { + name string + checks []string + }{{"--skip", o.skip}, {"--only", o.only}} { + for _, check := range flag.checks { + if !slices.Contains(healthChecks, check) { + return fmt.Errorf("invalid %s %q: must be one of %s", flag.name, check, strings.Join(healthChecks, ", ")) + } + } + } + return nil +} + +// isHTTPURL reports whether raw is an absolute http or https URL. +func isHTTPURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" +} + +// selected reports whether --skip and --only leave check in. +func (o *healthOperation) selected(check string) bool { + if len(o.only) > 0 { + return slices.Contains(o.only, check) + } + return !slices.Contains(o.skip, check) +} + +func (o *healthOperation) Run(ctx cmd.OperationContext) error { + if err := o.validate(); err != nil { + return err + } + + sdk, err := newClient(ctx.Config) + if err != nil { + return err + } + + intranetURL, err := o.resolveIntranetURL(ctx.Config) + if err != nil { + return err + } + + return o.run(ctx, sdk, runSpec{ + name: "health", + steps: o.steps(sdk.Transport(), intranetURL), + }) +} + +// resolveIntranetURL returns the URL the intranet check requests, or "" when +// the check is not selected. Without --intranet-url it is the US3 endpoint of +// the region the API calls go to, which has to be known. +func (o *healthOperation) resolveIntranetURL(cfg *config.Config) (string, error) { + if !o.selected("intranet") || o.intranetURL != "" { + return o.intranetURL, nil + } + region, ok := config.ResolveRegion(cfg) + if !ok { + return "", fmt.Errorf("cannot tell the region from domain %q to check its intranet; set the region or pass --intranet-url", cfg.Domain) + } + return intranetURLFor(region), nil +} + +// intranetURLFor returns the URL of region's internal US3 endpoint. +func intranetURLFor(region string) string { + if alias, ok := intranetRegionAliases[region]; ok { + region = alias + } + return fmt.Sprintf(intranetURLTemplate, region) +} + +// steps returns the steps of the selected checks, in the order of +// healthChecks. +func (o *healthOperation) steps(t *transport.Client, intranetURL string) []benchmark.Step[*benchSandbox] { + var internet []benchmark.Step[*benchSandbox] + for _, raw := range o.urls { + internet = append(internet, probeStep(benchmark.Phase("internet "+raw), raw)) + } + + port := o.publicURLPort + stepsOf := map[string][]benchmark.Step[*benchSandbox]{ + "exec": {execStep("echo ok", "")}, + "filesystem": {{Phase: phaseFilesystem, Run: checkFilesystem}}, + "internet": internet, + "intranet": {intranetStep(benchmark.Phase("intranet "+intranetURL), intranetURL)}, + "public-url": {{Phase: benchmark.Phase(fmt.Sprintf("public-url %d", port)), Run: func(ctx context.Context, sbx *benchSandbox) error { + return checkPublicURL(ctx, t, sbx, port) + }}}, + "pause": { + {Phase: phasePause, Run: checkPause}, + {Phase: phaseResume, Run: checkResume}, + }, + } + + var steps []benchmark.Step[*benchSandbox] + for _, check := range healthChecks { + if o.selected(check) { + steps = append(steps, stepsOf[check]...) + } + } + return steps +} + +// checkFilesystem writes a random token to a file through envd, reads it +// back and compares. +// +// The path is fixed: the random token in the content is what catches a +// mismatch, while a random path would put a different name in the error of +// every iteration, so the same failure would never group into one report row. +func checkFilesystem(ctx context.Context, sbx *benchSandbox) error { + token := randomToken() + const path = "/tmp/ucloud-sandbox-health" + + fs := sbx.Files() + if _, err := fs.Write(ctx, path, token); err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + got, err := fs.Read(ctx, path) + if err != nil { + return fmt.Errorf("read %s: %w", path, err) + } + if got != token { + return fmt.Errorf("read %s: got %q, wrote %q", path, got, token) + } + + // The sandbox is thrown away anyway; removing the file only keeps a long + // lived one tidy. + _ = fs.Remove(ctx, path) + + return nil +} + +// probeStep checks that the sandbox reaches target over HTTP and gets 200 +// back. +func probeStep(phase benchmark.Phase, target string) benchmark.Step[*benchSandbox] { + return benchmark.Step[*benchSandbox]{ + Phase: phase, + Run: func(ctx context.Context, sbx *benchSandbox) error { + result, err := sbx.run(ctx, probeCommand(target), "") + if err != nil { + return fmt.Errorf("%s: %w", target, err) + } + if err := checkHTTPCode(result.Stdout); err != nil { + return fmt.Errorf("%s: %w", target, err) + } + return nil + }, + } +} + +// probeCommand returns the curl invocation that prints the HTTP status code +// target answers with. curl fails, with a message on stderr, when the name +// does not resolve or the connection cannot be made. +func probeCommand(target string) string { + return fmt.Sprintf("curl -sS -o /dev/null -m %d -w '%%{http_code}' %s", probeTimeoutSec, shellQuote(target)) +} + +// checkHTTPCode checks the status code a probe printed is 200. curl prints +// 000 when no response arrived. Redirects are not followed, so a 3xx fails. +func checkHTTPCode(stdout string) error { + switch code := strings.TrimSpace(stdout); code { + case "200": + return nil + case "", "000": + return errors.New("no HTTP response") + default: + return fmt.Errorf("HTTP %s, want 200", code) + } +} + +// intranetStep checks that the sandbox gets an HTTP response from target. +// Its status does not matter: any response shows the sandbox reaches the +// service, and the default endpoint, US3, answers an anonymous request with +// 400. A failure tells how far the request got, so a slow name lookup can be +// told from a connection that never came. +func intranetStep(phase benchmark.Phase, target string) benchmark.Step[*benchSandbox] { + return benchmark.Step[*benchSandbox]{ + Phase: phase, + Run: func(ctx context.Context, sbx *benchSandbox) error { + // A failed command still comes with what curl printed. + result, err := sbx.run(ctx, intranetProbeCommand(target), "") + var code, timeline string + if result != nil { + code, timeline = parseIntranetProbe(result.Stdout) + } + if timeline != "" { + timeline = " (" + timeline + ")" + } + if err != nil { + return fmt.Errorf("%s: %w%s", target, err, timeline) + } + if code == "" || code == "000" { + return fmt.Errorf("%s: no HTTP response%s", target, timeline) + } + return nil + }, + } +} + +// intranetProbeCommand returns the curl invocation requesting target. It +// prints the status code, then the times, in seconds since the start, at +// which the name resolved, the connection was made and the first byte of the +// response arrived. curl prints them even when the request fails, with 000 +// and 0 for what never happened. +func intranetProbeCommand(target string) string { + return fmt.Sprintf("curl -sS -o /dev/null -m %d -w '%%{http_code} %%{time_namelookup} %%{time_connect} %%{time_starttransfer}' %s", + probeTimeoutSec, shellQuote(target)) +} + +// parseIntranetProbe splits what intranetProbeCommand printed into the status +// code and a description of when each stage of the request was reached, "" if +// the output is not what it prints. +func parseIntranetProbe(stdout string) (code, timeline string) { + fields := strings.Fields(stdout) + if len(fields) != 4 { + return "", "" + } + stages := []string{"resolved", "connected", "first byte"} + parts := make([]string, 0, len(stages)) + for i, stage := range stages { + sec, err := strconv.ParseFloat(fields[i+1], 64) + switch { + case err != nil: + return fields[0], "" + case sec == 0: + parts = append(parts, stage+" -") + default: + parts = append(parts, fmt.Sprintf("%s %s", stage, time.Duration(sec*float64(time.Second)).Round(time.Millisecond))) + } + } + return fields[0], strings.Join(parts, ", ") +} + +// shellQuote quotes s as a single word for the shell envd runs commands in. +func shellQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'"'"'`) + "'" +} + +// checkPublicURL serves a random token over HTTP inside the sandbox and +// fetches it from outside through the sandbox's public URL for port, the one +// `sandbox host` reports, checking the gateway's inbound path. +func checkPublicURL(ctx context.Context, t *transport.Client, sbx *benchSandbox, port int) error { + token := randomToken() + // Fixed, like the filesystem check's path, so failures group. + const dir = "/tmp/ucloud-sandbox-health-www" + + if _, err := sbx.Files().Write(ctx, dir+"/health", token); err != nil { + return fmt.Errorf("write served file: %w", err) + } + + server := fmt.Sprintf("python3 -m http.server %d --bind 0.0.0.0 --directory %s", port, shellQuote(dir)) + handle, err := sbx.Commands().Start(ctx, server, commands.Options{}) + if err != nil { + return fmt.Errorf("start HTTP server: %w", err) + } + defer func() { _, _ = handle.Kill(context.WithoutCancel(ctx)) }() + + // A server that dies, python3 missing say, would otherwise only show up as + // the gateway failing until the deadline. + // The watcher ends with the check, even when killing the server fails and + // its stream stays open. + watchCtx, stopWatch := context.WithCancel(ctx) + defer stopWatch() + + exited := make(chan string, 1) + go func() { + result, err := handle.Wait(watchCtx) + switch { + case err != nil: + exited <- err.Error() + case result != nil: + exited <- fmt.Sprintf("exit code %d: %s", result.ExitCode, result.Stderr) + default: + exited <- "exited" + } + }() + + // SandboxHost resolves the host the way envd traffic does, falling back to + // the configured domain when the reported one is not a domain. + var reportedDomain string + if sbx.Domain != nil { + reportedDomain = *sbx.Domain + } + target := t.SandboxScheme() + "://" + t.SandboxHost(sbx.ID(), reportedDomain, port) + "/health" + var trafficToken string + if sbx.TrafficAccessToken != nil { + trafficToken = *sbx.TrafficAccessToken + } + + pollCtx, cancel := context.WithTimeout(ctx, publicURLTimeout) + defer cancel() + + var last error + for { + body, err := fetch(pollCtx, t.HTTPClient(), target, trafficToken) + switch { + case err != nil: + last = err + case body != token: + return fmt.Errorf("GET %s: got %q, served %q", target, body, token) + default: + return nil + } + + select { + case reason := <-exited: + return fmt.Errorf("HTTP server in the sandbox stopped (%s); last attempt: %w", reason, last) + case <-pollCtx.Done(): + return fmt.Errorf("GET %s: no answer within %s: %w", target, publicURLTimeout, last) + case <-time.After(publicURLPollInterval): + } + } +} + +// fetch GETs target and returns its body, failing on any status but 200. +func fetch(ctx context.Context, client *http.Client, target, trafficToken string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return "", err + } + if trafficToken != "" { + req.Header.Set("E2B-Traffic-Access-Token", trafficToken) + } + + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if err != nil { + return "", err + } + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("GET %s: HTTP %d", target, resp.StatusCode) + } + return string(body), nil +} + +// checkPause pauses the sandbox. +func checkPause(ctx context.Context, sbx *benchSandbox) error { + if err := sbx.Pause(ctx, api.SandboxPauseRequest{}); err != nil { + return err + } + sbx.paused = true + return nil +} + +// checkResume resumes the paused sandbox and runs a command in it, so the +// resumed sandbox is known to work and not only to be reported running. +func checkResume(ctx context.Context, sbx *benchSandbox) error { + if !sbx.paused { + return notAttempted("the sandbox did not pause") + } + + resumed, err := sbx.svc.Connect(ctx, sbx.ID(), api.ConnectSandbox{Timeout: sbx.timeout}) + if err != nil { + return err + } + sbx.Sandbox = resumed + sbx.paused = false + + if _, err := sbx.run(ctx, "echo ok", ""); err != nil { + return fmt.Errorf("exec after resume: %w", err) + } + return nil +} + +// randomToken returns a random hex string, unique enough to name files and +// tell served content apart. +func randomToken() string { + b := make([]byte, 8) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} diff --git a/cmd/benchmark/health_test.go b/cmd/benchmark/health_test.go new file mode 100644 index 0000000..55ed5af --- /dev/null +++ b/cmd/benchmark/health_test.go @@ -0,0 +1,259 @@ +package benchmark + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-cli/internal/config" +) + +func parseHealth(t *testing.T, args ...string) *healthOperation { + t.Helper() + op := &healthOperation{} + require.NoError(t, op.Command().ParseFlags(args)) + return op +} + +func TestHealthDefaults(t *testing.T) { + op := parseHealth(t) + + assert.Equal(t, 1, op.count, "one sandbox by default") + assert.Equal(t, 1, op.concurrency) + assert.Equal(t, []string{"https://www.apple.com/library/test/success.html"}, op.urls) + assert.Empty(t, op.intranetURL, "resolved from the region") + assert.Equal(t, 8000, op.publicURLPort) + assert.NoError(t, op.validate()) +} + +func TestHealthValidate(t *testing.T) { + tests := []struct { + name string + args []string + err string + }{ + {"url without scheme", []string{"--url", "www.baidu.com"}, "--url"}, + {"ftp url", []string{"--url", "ftp://example.com"}, "--url"}, + {"port too low", []string{"--public-url-port", "0"}, "--public-url-port"}, + {"port too high", []string{"--public-url-port", "70000"}, "--public-url-port"}, + {"zero count", []string{"-n", "0"}, "--count"}, + {"duplicate url", []string{"--url", "https://a.com", "--url", "https://a.com"}, "duplicate --url"}, + {"intranet host without scheme", []string{"--intranet-url", "internal.s3-cn-sh2.ufileos.com"}, "--intranet-url"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := parseHealth(t, tt.args...).validate() + require.Error(t, err) + assert.Contains(t, err.Error(), tt.err) + }) + } + + op := parseHealth(t, "--url", "https://www.baidu.com", "--url", "http://example.com:8080/x", "-n", "20", "-c", "5") + assert.Equal(t, []string{"https://www.baidu.com", "http://example.com:8080/x"}, op.urls) + assert.NoError(t, op.validate()) + + assert.NoError(t, parseHealth(t, "--intranet-url", "http://10.0.0.1:8080/health").validate()) + + op = parseHealth(t, "--url", "https://example.com/api?ids=1,2") + assert.Equal(t, []string{"https://example.com/api?ids=1,2"}, op.urls, "a comma does not split the URL") + assert.NoError(t, op.validate()) +} + +func TestIntranetURLFor(t *testing.T) { + assert.Equal(t, "https://internal.s3-cn-wlcb.ufileos.com/", intranetURLFor("cn-wlcb")) + assert.Equal(t, "https://internal.s3-cn-sh2.ufileos.com/", intranetURLFor("cn-sh")) + assert.Equal(t, "https://internal.s3-us-ca.ufileos.com/", intranetURLFor("us-ca")) + assert.Equal(t, "https://internal.s3-us-den.ufileos.com/", intranetURLFor("us-den")) + assert.Equal(t, "https://internal.s3-vn-sng.ufileos.com/", intranetURLFor("vn-sng")) + + assert.Equal(t, "https://internal.s3-mars-1.ufileos.com/", intranetURLFor("mars-1"), + "a new region follows the naming pattern") +} + +func TestHealthSteps(t *testing.T) { + phases := func(steps []benchmark.Step[*benchSandbox]) []benchmark.Phase { + var out []benchmark.Phase + for _, s := range steps { + out = append(out, s.Phase) + } + return out + } + + op := parseHealth(t, "--url", "https://www.baidu.com", "--url", "https://example.com/path") + assert.Equal(t, []benchmark.Phase{ + "exec", + "filesystem", + "internet https://www.baidu.com", + "internet https://example.com/path", + "intranet https://internal.s3-cn-wlcb.ufileos.com/", + "public-url 8000", + "pause", + "resume", + }, phases(op.steps(nil, "https://internal.s3-cn-wlcb.ufileos.com/"))) +} + +func TestProbeCommand(t *testing.T) { + assert.Equal(t, + `curl -sS -o /dev/null -m 10 -w '%{http_code}' 'https://www.baidu.com'`, + probeCommand("https://www.baidu.com")) + assert.Equal(t, + `curl -sS -o /dev/null -m 10 -w '%{http_code}' 'http://x/'"'"'; rm -rf /'`, + probeCommand("http://x/'; rm -rf /"), "a quote in the URL cannot break out") +} + +func TestIntranetProbeCommand(t *testing.T) { + const format = `-w '%{http_code} %{time_namelookup} %{time_connect} %{time_starttransfer}'` + assert.Equal(t, + `curl -sS -o /dev/null -m 10 `+format+` 'https://internal.s3-cn-sh2.ufileos.com/'`, + intranetProbeCommand("https://internal.s3-cn-sh2.ufileos.com/")) + assert.Equal(t, + `curl -sS -o /dev/null -m 10 `+format+` 'http://x/'"'"'; rm -rf /'`, + intranetProbeCommand("http://x/'; rm -rf /"), "a quote in the URL cannot break out") +} + +func TestParseIntranetProbe(t *testing.T) { + tests := []struct { + name, stdout, code, timeline string + }{ + {"answered", "400 0.178443 0.178742 0.184301", "400", "resolved 178ms, connected 179ms, first byte 184ms"}, + {"no connection", "000 5.012 0.000000 0.000000", "000", "resolved 5.012s, connected -, first byte -"}, + {"name did not resolve", "000 0.000000 0.000000 0.000000", "000", "resolved -, connected -, first byte -"}, + {"not curl's output", "curl: not found", "", ""}, + {"empty", "", "", ""}, + {"bad time", "200 x 0.1 0.2", "200", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + code, timeline := parseIntranetProbe(tt.stdout) + assert.Equal(t, tt.code, code) + assert.Equal(t, tt.timeline, timeline) + }) + } +} + +func TestCheckHTTPCode(t *testing.T) { + assert.NoError(t, checkHTTPCode("200")) + assert.NoError(t, checkHTTPCode("200\n")) + + for _, code := range []string{"301", "403", "502"} { + err := checkHTTPCode(code) + require.Error(t, err, code) + assert.Equal(t, "HTTP "+code+", want 200", err.Error()) + } + + for _, out := range []string{"000", ""} { + err := checkHTTPCode(out) + require.Error(t, err, out) + assert.Equal(t, "no HTTP response", err.Error()) + } +} + +func TestFetch(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/health": + if r.Header.Get("E2B-Traffic-Access-Token") != "tok" { + w.WriteHeader(http.StatusForbidden) + return + } + _, _ = w.Write([]byte("token-123")) + default: + w.WriteHeader(http.StatusBadGateway) + } + })) + defer srv.Close() + + body, err := fetch(context.Background(), srv.Client(), srv.URL+"/health", "tok") + require.NoError(t, err) + assert.Equal(t, "token-123", body) + + _, err = fetch(context.Background(), srv.Client(), srv.URL+"/health", "") + require.Error(t, err, "the traffic token is sent when given") + assert.Contains(t, err.Error(), "HTTP 403") + + _, err = fetch(context.Background(), srv.Client(), srv.URL+"/starting", "tok") + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 502") +} + +func healthPhases(t *testing.T, args ...string) []benchmark.Phase { + t.Helper() + op := parseHealth(t, args...) + require.NoError(t, op.validate()) + var out []benchmark.Phase + for _, s := range op.steps(nil, "https://internal.s3-cn-wlcb.ufileos.com/") { + out = append(out, s.Phase) + } + return out +} + +func TestHealthSelectChecks(t *testing.T) { + assert.Equal(t, []benchmark.Phase{"internet " + defaultInternetURL, "intranet https://internal.s3-cn-wlcb.ufileos.com/"}, + healthPhases(t, "--only", "internet,intranet")) + + assert.Equal(t, []benchmark.Phase{"exec", "intranet https://internal.s3-cn-wlcb.ufileos.com/"}, + healthPhases(t, "--only", "intranet", "--only", "exec"), + "checks run in their fixed order, whatever the order given") + + assert.Equal(t, []benchmark.Phase{"pause", "resume"}, healthPhases(t, "--only", "pause"), + "pause covers resume") + + assert.Equal(t, []benchmark.Phase{ + "exec", "filesystem", "internet " + defaultInternetURL, "intranet https://internal.s3-cn-wlcb.ufileos.com/", + }, healthPhases(t, "--skip", "pause,public-url")) +} + +func TestHealthEveryCheckHasSteps(t *testing.T) { + for _, check := range healthChecks { + assert.NotEmpty(t, healthPhases(t, "--only", check), check) + } +} + +func TestHealthValidateChecks(t *testing.T) { + err := parseHealth(t, "--skip", "pause", "--only", "exec").validate() + require.Error(t, err) + assert.Equal(t, "--skip and --only cannot be used together", err.Error()) + + err = parseHealth(t, "--skip", "resume").validate() + require.Error(t, err) + assert.Equal(t, `invalid --skip "resume": must be one of exec, filesystem, internet, intranet, public-url, pause`, err.Error()) + + err = parseHealth(t, "--only", "dns").validate() + require.Error(t, err) + assert.Contains(t, err.Error(), `invalid --only "dns"`) +} + +func TestHealthPublicURLNamesItsPort(t *testing.T) { + assert.Equal(t, []benchmark.Phase{"public-url 3000"}, + healthPhases(t, "--only", "public-url", "--public-url-port", "3000")) +} + +func TestHealthResolveIntranetURL(t *testing.T) { + cfg := func(region, domain string) *config.Config { + return &config.Config{Region: region, Domain: domain} + } + + host, err := parseHealth(t).resolveIntranetURL(cfg("", "cn-sh.sandbox.ucloudai.com")) + require.NoError(t, err) + assert.Equal(t, "https://internal.s3-cn-sh2.ufileos.com/", host, "the region comes from the domain the API calls go to") + + host, err = parseHealth(t).resolveIntranetURL(cfg("us-ca", "")) + require.NoError(t, err) + assert.Equal(t, "https://internal.s3-us-ca.ufileos.com/", host) + + _, err = parseHealth(t).resolveIntranetURL(cfg("", "sandbox.example.com")) + require.Error(t, err, "a custom domain alone does not tell the region") + assert.Contains(t, err.Error(), "--intranet-url") + + host, err = parseHealth(t, "--intranet-url", "http://10.0.0.1:8080/").resolveIntranetURL(cfg("", "sandbox.example.com")) + require.NoError(t, err) + assert.Equal(t, "http://10.0.0.1:8080/", host, "the flag wins") + + host, err = parseHealth(t, "--skip", "intranet").resolveIntranetURL(cfg("", "sandbox.example.com")) + require.NoError(t, err, "the region is not needed when the intranet check is skipped") + assert.Empty(t, host) +} diff --git a/cmd/benchmark/lifecycle.go b/cmd/benchmark/lifecycle.go new file mode 100644 index 0000000..ea6be18 --- /dev/null +++ b/cmd/benchmark/lifecycle.go @@ -0,0 +1,57 @@ +package benchmark + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" +) + +type lifecycleOperation struct { + runOptions + + command string + user string + skipExec bool +} + +func (o *lifecycleOperation) Command() *cobra.Command { + c := &cobra.Command{ + Use: "lifecycle", + Short: "Measure sandbox create, first exec and kill latency", + Args: cobra.NoArgs, + } + + o.addFlags(c, 10, "Seconds each sandbox lives for, bounding any sandbox a failed kill leaves behind") + c.Flags().StringVarP(&o.command, "cmd", "", "echo ok", "Command run in each sandbox during the exec phase") + c.Flags().StringVarP(&o.user, "user", "u", "", "User to run the exec command as") + c.Flags().BoolVarP(&o.skipExec, "skip-exec", "", false, "Skip the exec phase, measuring create and kill only") + + return c +} + +func (o *lifecycleOperation) validate() error { + if err := o.runOptions.validate(); err != nil { + return err + } + if !o.skipExec && o.command == "" { + return fmt.Errorf("--cmd cannot be empty; use --skip-exec to leave out the exec phase") + } + return nil +} + +func (o *lifecycleOperation) Run(ctx cmd.OperationContext) error { + if err := o.validate(); err != nil { + return err + } + sdk, err := newClient(ctx.Config) + if err != nil { + return err + } + + spec := runSpec{name: "lifecycle"} + if !o.skipExec { + spec.steps = append(spec.steps, execStep(o.command, o.user)) + } + return o.run(ctx, sdk, spec) +} diff --git a/cmd/benchmark/run.go b/cmd/benchmark/run.go new file mode 100644 index 0000000..580aa68 --- /dev/null +++ b/cmd/benchmark/run.go @@ -0,0 +1,323 @@ +package benchmark + +import ( + "context" + "fmt" + "io" + "math/rand/v2" + "os" + "os/signal" + "syscall" + "time" + + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-cli/internal/config" + "github.com/ucloud/ucloud-sandbox-cli/internal/list" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/api" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/client" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox/commands" + "golang.org/x/term" +) + +// runIDMetadataKey tags every sandbox a run creates, so the ones it leaves +// behind can be found and cleaned up. +const runIDMetadataKey = "benchmark" + +// manageBy is the SDK manage-by marker set on every sandbox a benchmark +// creates, telling them apart from sandboxes opened by other products. +const manageBy = "sandbox-bench" + +// runOptions are the flags shared by every benchmark command. +type runOptions struct { + template string + count int + concurrency int + timeout int32 + format string + output string + breakdown bool +} + +// addFlags registers the shared flags on c. defaultCount is the number of +// iterations run when --count is not given, and timeoutUsage describes what +// the sandbox timeout means for the command. +func (o *runOptions) addFlags(c *cobra.Command, defaultCount int, timeoutUsage string) { + c.Flags().StringVarP(&o.template, "template", "t", "system/base", "Template ID or alias to create sandboxes from") + c.Flags().IntVarP(&o.count, "count", "n", defaultCount, "Total number of iterations") + c.Flags().IntVarP(&o.concurrency, "concurrency", "c", 1, "Number of iterations in flight at once") + c.Flags().Int32VarP(&o.timeout, "timeout", "", 300, timeoutUsage) + c.Flags().StringVarP(&o.format, "format", "f", list.FormatPretty, "Output format (pretty, json)") + c.Flags().StringVarP(&o.output, "output", "o", "", + "Also write the JSON report to this file, whatever --format prints") + c.Flags().BoolVarP(&o.breakdown, "breakdown", "", false, + "Show each phase's full latency, split into connection setup (DNS, dial, TLS) and service time") +} + +func (o *runOptions) validate() error { + if o.count < 1 { + return fmt.Errorf("invalid --count %d: must be 1 or greater", o.count) + } + if o.concurrency < 1 { + return fmt.Errorf("invalid --concurrency %d: must be 1 or greater", o.concurrency) + } + if o.timeout < 1 { + return fmt.Errorf("invalid --timeout %d: must be 1 or greater", o.timeout) + } + switch o.format { + case list.FormatPretty, list.FormatJSON: + default: + return fmt.Errorf("invalid --format %q: must be %s or %s", o.format, list.FormatPretty, list.FormatJSON) + } + return nil +} + +// runSpec describes what a benchmark command times on every sandbox. +type runSpec struct { + // name labels the run in its progress output. + name string + + // steps run on every sandbox between create and kill. + steps []benchmark.Step[*benchSandbox] + + // skipKill leaves the sandboxes running until their timeout. + skipKill bool + + // snapshots marks a run that takes snapshots, which outlive it unless + // deleted. leakedSnapshots, when set, returns the ones it failed to delete. + snapshots bool + leakedSnapshots func() []string +} + +// newClient returns the SDK client benchmarks run on: the configured one, +// with the retry of rate-limited requests turned off. +func newClient(cfg *config.Config) (*client.Client, error) { + return config.NewClient(cfg, withoutRetries) +} + +// run executes a benchmark and writes its report. +func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runSpec) error { + runID := newRunID(time.Now()) + cleanup := cleanupCommand(runID) + + runCtx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer stop() + + // The first Ctrl+C stops new iterations and waits for the ones in flight + // to finish; restoring the default handling lets a second one force the + // process out. + finished := make(chan struct{}) + defer close(finished) + go reportInterruption(runCtx, finished, stop, os.Stderr, cleanup) + + // A path that cannot be written is reported before the first sandbox is + // created, rather than after the whole run. + if o.output != "" { + if err := checkReportFile(o.output); err != nil { + return err + } + } + + o.writeHeader(os.Stderr, spec, runID) + + showProgress := term.IsTerminal(int(os.Stderr.Fd())) + + opts := benchmark.Options[*benchSandbox]{ + Count: o.count, + Concurrency: o.concurrency, + Steps: spec.steps, + SkipKill: spec.skipKill, + OnIteration: func(p benchmark.Progress) { + if showProgress { + fmt.Fprintf(os.Stderr, "\r[%d/%d] succeeded %d, failed %d", p.Done, p.Total, p.Succeeded, p.Failed) + } + }, + } + + report := benchmark.Run(runCtx, newCreator(sdk.Sandboxes(), runID, o.template, o.timeout), opts) + if showProgress && report.Started > 0 { + fmt.Fprintln(os.Stderr) + } + + view := newRunView(runID, o.template, o.concurrency, o.timeout, report) + if spec.leakedSnapshots != nil { + view.LeakedSnapshots = append(view.LeakedSnapshots, spec.leakedSnapshots()...) + } + view.breakdown = o.breakdown + if spec.skipKill && len(report.Phases) > 0 { + view.LeftRunning = report.Phases[0].Stats.Count + } + + if o.format == list.FormatJSON { + if err := cmd.ShowJSON(view); err != nil { + return err + } + } else if err := view.writePretty(os.Stdout); err != nil { + return err + } + + // The file is written after the report is printed, and even when + // iterations failed, so the run's results are never lost to a write that + // goes wrong at the end. + if o.output != "" { + if err := view.writeJSONFile(o.output); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "Report saved to %s\n", o.output) + } + + return exitError(report) +} + +// reportInterruption waits for ctx to be cancelled and, unless finished is +// closed first, restores the default signal handling, so a second Ctrl+C +// quits at once, and announces how to clean up after the run. +func reportInterruption(ctx context.Context, finished <-chan struct{}, stop func(), w io.Writer, cleanup string) { + select { + case <-ctx.Done(): + case <-finished: + return + } + + // A run can finish in the same instant its context is cancelled, leaving + // both channels ready for the select above to pick between at random. A + // run that closed finished before it could announce anything was not + // interrupted. + select { + case <-finished: + return + default: + } + + stop() + fmt.Fprintf(w, "\nInterrupted: waiting for in-flight iterations to finish (Ctrl+C again to force quit, then clean up with: %s)...\n", cleanup) +} + +// writeHeader describes the run about to start. The cleanup command is given +// up front, so a run that is killed outright still leaves a way to find its +// sandboxes. +func (o *runOptions) writeHeader(w io.Writer, spec runSpec, runID string) { + fmt.Fprintf(w, "Running %s benchmark %s\n", spec.name, runID) + fmt.Fprintf(w, " Template: %s\n", o.template) + fmt.Fprintf(w, " Iterations: %d (concurrency %d)\n", o.count, o.concurrency) + fmt.Fprintf(w, " Sandbox tag: %s=%s\n", runIDMetadataKey, runID) + if spec.snapshots { + fmt.Fprintf(w, " Snapshots: named %s\n", snapshotNamePrefix(runID)) + } + fmt.Fprintf(w, " Cleanup: %s\n", cleanupCommand(runID)) + if spec.snapshots { + fmt.Fprintf(w, " ucloud-sandbox-cli snapshot delete \n") + } + fmt.Fprintln(w) +} + +// exitError turns a report into the command's error, so scripts can tell a +// clean run from one that failed or was cut short. +func exitError(r benchmark.Report) error { + switch { + case r.Interrupted: + return fmt.Errorf("interrupted: %d of %d iteration(s) started, %d failed", r.Started, r.Requested, r.Failed) + case r.Failed > 0: + return fmt.Errorf("%d of %d iteration(s) failed", r.Failed, r.Started) + default: + return nil + } +} + +// newRunID returns the ID tagging the sandboxes of one run. The start time +// keeps it readable; the random suffix keeps runs started within the same +// second apart, so cleaning up one run never touches another. +func newRunID(now time.Time) string { + return fmt.Sprintf("%s-%06x", now.Format("20060102-150405"), rand.Uint32()&0xffffff) +} + +// cleanupCommand returns the command that kills every sandbox of a run. +func cleanupCommand(runID string) string { + return fmt.Sprintf("ucloud-sandbox-cli sandbox kill --all -m %s=%s", runIDMetadataKey, runID) +} + +// withoutRetries turns off the SDK's retry of rate-limited (429) requests. A +// retry waits out the Retry-After inside the call being timed, so it would +// pass rate limiting off as latency; failing instead shows it in the errors. +func withoutRetries(opts *client.Options) { + retries := 0 + opts.Retries = &retries +} + +// newCreator returns the CreateFunc that starts the sandboxes of a run. +func newCreator(svc *sandbox.Service, runID, template string, timeout int32) benchmark.CreateFunc[*benchSandbox] { + return func(ctx context.Context) (*benchSandbox, error) { + created, err := svc.Create(ctx, sandboxRequest(template, runID, timeout), manageBy) + if err != nil { + return nil, err + } + + return &benchSandbox{Sandbox: created, svc: svc, runID: runID, timeout: timeout}, nil + } +} + +// sandboxRequest returns the request creating a sandbox of a run from +// template, which may also be a snapshot ID. +func sandboxRequest(template, runID string, timeout int32) api.NewSandbox { + return api.NewSandbox{ + TemplateID: template, + Timeout: &timeout, + Metadata: &api.SandboxMetadata{runIDMetadataKey: runID}, + } +} + +// benchSandbox is the sandbox one iteration works on. It embeds the SDK +// sandbox, so the steps use its files, commands and fields directly. +type benchSandbox struct { + *sandbox.Sandbox + + // svc, runID and timeout let the steps start, connect to and tag further + // sandboxes of the run. + svc *sandbox.Service + runID string + timeout int32 + + // paused records that the pause step succeeded, so the resume step can + // tell a resume from a connect to a sandbox that never paused. + paused bool + + // snap is what the snapshot steps hand to the ones after them. + snap snapshotState +} + +func (sbx *benchSandbox) ID() string { + return sbx.SandboxID +} + +// run runs command in the sandbox as user. A non-zero exit is an error. +func (sbx *benchSandbox) run(ctx context.Context, command, user string) (*commands.Result, error) { + return sbx.Commands().User(user).Run(ctx, command, commands.Options{}) +} + +// Kill shadows the SDK's Sandbox.Kill to fit benchmark.Sandbox. It relies on +// the SDK's contract: (false, nil) is returned only when DELETE +// /sandboxes/{id} answers 404, and every other failure comes back as an +// error. That is what lets !killed be reported as not found. +func (sbx *benchSandbox) Kill(ctx context.Context) error { + killed, err := sbx.Sandbox.Kill(ctx) + if err != nil { + return err + } + if !killed { + return benchmark.ErrSandboxNotFound + } + return nil +} + +// execStep runs command in the sandbox; a non-zero exit fails it. +func execStep(command, user string) benchmark.Step[*benchSandbox] { + return benchmark.Step[*benchSandbox]{ + Phase: benchmark.PhaseExec, + Run: func(ctx context.Context, sbx *benchSandbox) error { + _, err := sbx.run(ctx, command, user) + return err + }, + } +} diff --git a/cmd/benchmark/snapshot.go b/cmd/benchmark/snapshot.go new file mode 100644 index 0000000..da61f81 --- /dev/null +++ b/cmd/benchmark/snapshot.go @@ -0,0 +1,306 @@ +package benchmark + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/api" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/sandbox/commands" +) + +// Phases of a snapshot benchmark, besides create and kill. +const ( + phaseWrite benchmark.Phase = "write" + phaseSnapshot benchmark.Phase = "snapshot" + phaseRestore benchmark.Phase = "restore" + phaseRestoreVerify benchmark.Phase = "restore-verify" + phaseFork benchmark.Phase = "fork" + phaseForkVerify benchmark.Phase = "fork-verify" + phaseSnapshotDelete benchmark.Phase = "snapshot-delete" + + // phaseCleanup kills the copies. It is not timed, and has no row of its + // own; it only shows up when it fails. + phaseCleanup benchmark.Phase = "cleanup" +) + +// copyPlaceholder stands in for a copy's sandbox ID in error messages, so the +// same failure in different copies groups together. +const copyPlaceholder = "" + +// tokenFile is where the write step leaves its token. It is in the user's +// home, expanded by the sandbox's shell, so the snapshot is sure to keep it. +const tokenFile = `"$HOME/.ucloud-sandbox-bench-token"` + +// snapshotState is what the snapshot steps of one iteration hand to the ones +// after them. An empty field means the step producing it did not succeed. +type snapshotState struct { + token string + + // snapshotID boots the snapshot; snapshotName, the name it was taken + // under, is what deletes it. + snapshotID string + snapshotName string + + restored *sandbox.Sandbox + forkedID string +} + +// snapshotOperation times snapshotting a sandbox, booting a sandbox from the +// snapshot and forking it, checking that both copies keep its files. +type snapshotOperation struct { + runOptions +} + +func (o *snapshotOperation) Command() *cobra.Command { + c := &cobra.Command{ + Use: "snapshot", + Short: "Measure snapshot, restore, fork and snapshot delete latency, checking copies keep the sandbox's files", + Args: cobra.NoArgs, + } + + o.addFlags(c, 3, "Seconds each sandbox lives for, bounding any sandbox a failed kill leaves behind") + + return c +} + +func (o *snapshotOperation) Run(ctx cmd.OperationContext) error { + if err := o.validate(); err != nil { + return err + } + + sdk, err := newClient(ctx.Config) + if err != nil { + return err + } + + leaked := &idList{} + + return o.run(ctx, sdk, runSpec{ + name: "snapshot", + steps: snapshotSteps(leaked), + snapshots: true, + leakedSnapshots: leaked.list, + }) +} + +// snapshotNamePrefix starts the name of every snapshot a run takes, so the +// ones it fails to delete can be told apart in `snapshot list`. +func snapshotNamePrefix(runID string) string { + return "bench-" + runID + "-" +} + +// snapshotSteps returns the steps of a snapshot iteration. The copies are +// killed before the snapshot is deleted, so the delete is timed as it is +// normally made, with nothing booted from the snapshot still running. +// Snapshots that cannot be deleted are added to leaked. +func snapshotSteps(leaked *idList) []benchmark.Step[*benchSandbox] { + return []benchmark.Step[*benchSandbox]{ + {Phase: phaseWrite, Run: writeToken}, + {Phase: phaseSnapshot, Run: takeSnapshot}, + {Phase: phaseRestore, Run: restoreSnapshot}, + {Phase: phaseRestoreVerify, Run: verifyRestored}, + {Phase: phaseFork, Run: forkSandbox}, + {Phase: phaseForkVerify, Run: verifyForked}, + {Phase: phaseCleanup, Run: killCopies, Untimed: true}, + {Phase: phaseSnapshotDelete, Run: func(ctx context.Context, sbx *benchSandbox) error { + return deleteSnapshot(ctx, sbx, leaked) + }}, + } +} + +// errNotAttempted marks the failure of a step that sent no request, because +// a step it depends on did not succeed. +var errNotAttempted = errors.New("not attempted") + +// notAttempted fails a step that depends on one that did not succeed. +func notAttempted(reason string) error { + return fmt.Errorf("%w: %s", errNotAttempted, reason) +} + +// writeToken leaves a random token in the sandbox for the copies to carry. +func writeToken(ctx context.Context, sbx *benchSandbox) error { + token := randomToken() + if _, err := sbx.run(ctx, fmt.Sprintf("printf %%s %s > %s", token, tokenFile), ""); err != nil { + return err + } + sbx.snap.token = token + return nil +} + +// takeSnapshot snapshots the sandbox under a name tied to the run. +func takeSnapshot(ctx context.Context, sbx *benchSandbox) error { + name := snapshotNamePrefix(sbx.runID) + sbx.ID() + info, err := sbx.svc.CreateSnapshot(ctx, sbx.ID(), api.SandboxSnapshotRequest{Name: &name}) + if err != nil { + return err + } + sbx.snap.snapshotID = info.SnapshotID + sbx.snap.snapshotName = name + return nil +} + +// restoreSnapshot boots a sandbox from the snapshot. +func restoreSnapshot(ctx context.Context, sbx *benchSandbox) error { + if sbx.snap.snapshotID == "" { + return notAttempted("no snapshot was taken") + } + restored, err := sbx.svc.Create(ctx, sandboxRequest(sbx.snap.snapshotID, sbx.runID, sbx.timeout), manageBy) + if err != nil { + return err + } + sbx.snap.restored = restored + return nil +} + +// verifyRestored checks the sandbox booted from the snapshot holds the token. +func verifyRestored(ctx context.Context, sbx *benchSandbox) error { + if sbx.snap.restored == nil { + return notAttempted("no sandbox was restored") + } + return withoutID(verifyToken(ctx, sbx.snap.restored, sbx.snap.token), sbx.snap.restored.SandboxID) +} + +// forkSandbox forks one copy of the sandbox. +// +// The fork request carries no metadata, but the service copies the source's +// metadata to its forks, run ID tag included. That is what lets the cleanup +// command, which kills by the tag, also reach a fork this step lost track of. +func forkSandbox(ctx context.Context, sbx *benchSandbox) error { + count := int32(1) + results, err := sbx.svc.Fork(ctx, sbx.ID(), api.SandboxForkRequest{Count: &count, Timeout: &sbx.timeout}) + if err != nil { + return err + } + if len(results) != 1 { + return fmt.Errorf("asked for 1 fork, got %d results", len(results)) + } + switch result := results[0]; { + case result.Error != nil: + return fmt.Errorf("fork failed: %s", result.Error.Message) + case result.Sandbox == nil: + return errors.New("fork reported neither a sandbox nor an error") + default: + sbx.snap.forkedID = result.Sandbox.SandboxID + return nil + } +} + +// verifyForked connects to the fork and checks it holds the token. +func verifyForked(ctx context.Context, sbx *benchSandbox) error { + if sbx.snap.forkedID == "" { + return notAttempted("no sandbox was forked") + } + forked, err := sbx.svc.Connect(ctx, sbx.snap.forkedID, api.ConnectSandbox{Timeout: sbx.timeout}) + if err != nil { + return withoutID(fmt.Errorf("connect to fork: %w", err), sbx.snap.forkedID) + } + return withoutID(verifyToken(ctx, forked, sbx.snap.token), sbx.snap.forkedID) +} + +// verifyToken checks that copy holds the token written to the original. +func verifyToken(ctx context.Context, copy *sandbox.Sandbox, token string) error { + if token == "" { + return notAttempted("no token was written") + } + result, err := copy.Commands().Run(ctx, "cat "+tokenFile, commands.Options{}) + if err != nil { + return err + } + // The tokens are random, so they stay out of the message to let the same + // failure in different iterations group together. + if strings.TrimSpace(result.Stdout) != token { + return errors.New("token mismatch: the copy does not hold what was written to the original") + } + return nil +} + +// withoutID replaces a copy's sandbox ID in err's message with a placeholder. +// The runner only knows the original sandbox's ID, so it cannot do this for +// the copies. +func withoutID(err error, id string) error { + if err == nil || id == "" || !strings.Contains(err.Error(), id) { + return err + } + return errors.New(strings.ReplaceAll(err.Error(), id, copyPlaceholder)) +} + +// deleteSnapshot deletes the snapshot, adding its name to leaked when that +// fails. +// +// The snapshot is deleted by the name it was taken under. DELETE +// /templates/{id} does not find a named snapshot by the ID it was created +// with ("/:"), nor without the tag, and answers 404. +// +// A 404 is a failure too, and leaks the snapshot: unlike a sandbox, a +// snapshot never expires, so one taken moments ago that cannot be found is +// one the request missed, not one that is gone. +func deleteSnapshot(ctx context.Context, sbx *benchSandbox, leaked *idList) error { + name := sbx.snap.snapshotName + if name == "" { + return notAttempted("no snapshot was taken") + } + deleted, err := sbx.svc.DeleteSnapshot(ctx, name) + if err != nil { + leaked.add(name) + return err + } + // Like Sandbox.Kill, DeleteSnapshot reports a 404 as (false, nil). + if !deleted { + leaked.add(name) + return errors.New("snapshot not found (HTTP 404)") + } + return nil +} + +// killCopies kills the restored and forked sandboxes, reporting the ones it +// could not kill in a benchmark.LeakedError. A copy that is already gone needs +// no cleanup. +func killCopies(ctx context.Context, sbx *benchSandbox) error { + var ids []string + if sbx.snap.restored != nil { + ids = append(ids, sbx.snap.restored.SandboxID) + } + if sbx.snap.forkedID != "" { + ids = append(ids, sbx.snap.forkedID) + } + + var leaked []string + var first error + for _, id := range ids { + if _, err := sbx.svc.Kill(ctx, id); err != nil { + leaked = append(leaked, id) + if first == nil { + first = withoutID(err, id) + } + } + } + if len(leaked) > 0 { + return &benchmark.LeakedError{IDs: leaked, Err: first} + } + return nil +} + +// idList collects IDs from concurrent iterations. +type idList struct { + mu sync.Mutex + ids []string +} + +func (l *idList) add(id string) { + l.mu.Lock() + defer l.mu.Unlock() + l.ids = append(l.ids, id) +} + +func (l *idList) list() []string { + l.mu.Lock() + defer l.mu.Unlock() + return append([]string(nil), l.ids...) +} diff --git a/cmd/benchmark/snapshot_test.go b/cmd/benchmark/snapshot_test.go new file mode 100644 index 0000000..3782660 --- /dev/null +++ b/cmd/benchmark/snapshot_test.go @@ -0,0 +1,310 @@ +package benchmark + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/api" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/client" +) + +// fakeControlPlane answers the control-plane requests of the snapshot steps +// and records what it was asked. +type fakeControlPlane struct { + mu sync.Mutex + + creates []api.NewSandbox + snapshots []api.SandboxSnapshotRequest + killed []string + deleted []string + + // Statuses to answer with instead of success. + forkError string + deleteSnapshot int + killStatus int +} + +func (f *fakeControlPlane) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + + sandboxJSON := func(id string) string { + return `{"sandboxID":"` + id + `","templateID":"tpl","clientID":"c","envdVersion":"0.2.0"}` + } + created := func(body string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(body)) + } + + path := r.URL.Path + switch { + case r.Method == http.MethodPost && path == "/sandboxes": + var req api.NewSandbox + _ = json.NewDecoder(r.Body).Decode(&req) + f.creates = append(f.creates, req) + created(sandboxJSON("sbx-" + string(rune('a'+len(f.creates)-1)))) + + case r.Method == http.MethodPost && strings.HasSuffix(path, "/snapshots"): + var req api.SandboxSnapshotRequest + _ = json.NewDecoder(r.Body).Decode(&req) + f.snapshots = append(f.snapshots, req) + created(`{"snapshotID":"team/` + *req.Name + `:default","names":["team/` + *req.Name + `:default"]}`) + + case r.Method == http.MethodPost && strings.HasSuffix(path, "/fork"): + if f.forkError != "" { + created(`[{"error":{"code":500,"message":"` + f.forkError + `"}}]`) + return + } + created(`[{"sandbox":` + sandboxJSON("sbx-fork") + `}]`) + + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/templates/"): + ref := strings.TrimPrefix(path, "/templates/") + f.deleted = append(f.deleted, ref) + // As the service does, a named snapshot is only found by its bare + // name, not by the "/:" ID it was created with. + if strings.ContainsAny(ref, "/:") { + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(statusOr(f.deleteSnapshot, http.StatusNoContent)) + + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/sandboxes/"): + f.killed = append(f.killed, strings.TrimPrefix(path, "/sandboxes/")) + w.WriteHeader(statusOr(f.killStatus, http.StatusNoContent)) + + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func statusOr(status, fallback int) int { + if status != 0 { + return status + } + return fallback +} + +// newFakeSandbox creates a benchSandbox of run-1 against fake. +func newFakeSandbox(t *testing.T, fake *fakeControlPlane) *benchSandbox { + t.Helper() + srv := httptest.NewServer(fake) + t.Cleanup(srv.Close) + + sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) + require.NoError(t, err) + + sbx, err := newCreator(sdk.Sandboxes(), "run-1", "system/base", 300)(context.Background()) + require.NoError(t, err) + return sbx +} + +func TestSnapshotStepsAgainstFakeService(t *testing.T) { + fake := &fakeControlPlane{} + sbx := newFakeSandbox(t, fake) + ctx := context.Background() + leaked := &idList{} + + require.NoError(t, takeSnapshot(ctx, sbx)) + require.Len(t, fake.snapshots, 1) + assert.Equal(t, "bench-run-1-sbx-a", *fake.snapshots[0].Name, "named after the run and the sandbox") + assert.Equal(t, "team/bench-run-1-sbx-a:default", sbx.snap.snapshotID) + + require.NoError(t, restoreSnapshot(ctx, sbx)) + require.Len(t, fake.creates, 2) + restore := fake.creates[1] + assert.Equal(t, "team/bench-run-1-sbx-a:default", restore.TemplateID, "booted from the snapshot") + assert.Equal(t, "run-1", (*restore.Metadata)[runIDMetadataKey], "tagged with the run, so cleanup finds it") + require.NotNil(t, sbx.snap.restored) + + require.NoError(t, forkSandbox(ctx, sbx)) + assert.Equal(t, "sbx-fork", sbx.snap.forkedID) + + require.NoError(t, deleteSnapshot(ctx, sbx, leaked)) + assert.Equal(t, []string{"bench-run-1-sbx-a"}, fake.deleted, "deleted by name, not by ID") + assert.Empty(t, leaked.list()) + + require.NoError(t, killCopies(ctx, sbx)) + assert.Equal(t, []string{"sbx-b", "sbx-fork"}, fake.killed, "both copies are killed, the original is not") +} + +func TestForkSandboxReportsFailedFork(t *testing.T) { + sbx := newFakeSandbox(t, &fakeControlPlane{forkError: "no capacity"}) + + err := forkSandbox(context.Background(), sbx) + require.Error(t, err) + assert.Equal(t, "fork failed: no capacity", err.Error()) + assert.Empty(t, sbx.snap.forkedID) +} + +func TestDeleteSnapshotFailures(t *testing.T) { + taken := func(sbx *benchSandbox) { + sbx.snap.snapshotID = "team/bench-run-1-sbx-a:default" + sbx.snap.snapshotName = "bench-run-1-sbx-a" + } + + t.Run("server error leaks the snapshot", func(t *testing.T) { + sbx := newFakeSandbox(t, &fakeControlPlane{deleteSnapshot: http.StatusInternalServerError}) + taken(sbx) + leaked := &idList{} + + require.Error(t, deleteSnapshot(context.Background(), sbx, leaked)) + assert.Equal(t, []string{"bench-run-1-sbx-a"}, leaked.list(), "leaked by the name that deletes it") + }) + + t.Run("not found leaks the snapshot too", func(t *testing.T) { + sbx := newFakeSandbox(t, &fakeControlPlane{deleteSnapshot: http.StatusNotFound}) + taken(sbx) + leaked := &idList{} + + err := deleteSnapshot(context.Background(), sbx, leaked) + require.Error(t, err) + assert.Equal(t, "snapshot not found (HTTP 404)", err.Error()) + assert.Equal(t, []string{"bench-run-1-sbx-a"}, leaked.list(), + "a snapshot taken moments ago does not expire; a 404 means the request missed it") + }) +} + +func TestKillCopiesReportsWhatItCannotKill(t *testing.T) { + fake := &fakeControlPlane{} + sbx := newFakeSandbox(t, fake) + sbx.snap.forkedID = "sbx-fork" + fake.killStatus = http.StatusInternalServerError + + err := killCopies(context.Background(), sbx) + var leaked *benchmark.LeakedError + require.ErrorAs(t, err, &leaked) + assert.Equal(t, []string{"sbx-fork"}, leaked.IDs) + assert.NotContains(t, err.Error(), "sbx-fork", "the message groups across copies") +} + +func TestSnapshotStepsNotAttempted(t *testing.T) { + ctx := context.Background() + sbx := &benchSandbox{} + + for name, run := range map[string]func() error{ + "restore": func() error { return restoreSnapshot(ctx, sbx) }, + "restore-verify": func() error { return verifyRestored(ctx, sbx) }, + "fork-verify": func() error { return verifyForked(ctx, sbx) }, + "snapshot-delete": func() error { return deleteSnapshot(ctx, sbx, &idList{}) }, + } { + err := run() + require.Error(t, err, name) + assert.True(t, strings.HasPrefix(err.Error(), "not attempted: "), "%s: %v", name, err) + assert.ErrorIs(t, err, errNotAttempted, name) + } + + assert.NoError(t, killCopies(ctx, sbx), "nothing to clean up") +} + +func TestSnapshotStepOrder(t *testing.T) { + var phases []benchmark.Phase + var untimed []benchmark.Phase + for _, s := range snapshotSteps(&idList{}) { + phases = append(phases, s.Phase) + if s.Untimed { + untimed = append(untimed, s.Phase) + } + } + assert.Equal(t, []benchmark.Phase{ + "write", "snapshot", "restore", "restore-verify", "fork", "fork-verify", "cleanup", "snapshot-delete", + }, phases, "the copies are gone before the snapshot is deleted") + assert.Equal(t, []benchmark.Phase{"cleanup"}, untimed) +} + +func TestWithoutID(t *testing.T) { + assert.NoError(t, withoutID(nil, "sbx-1")) + + err := errors.New(`Post "https://49983-sbx-1.example.com/process.Process/Start": refused`) + assert.Equal(t, `Post "https://49983-.example.com/process.Process/Start": refused`, withoutID(err, "sbx-1").Error()) + + unrelated := errors.New("timeout") + assert.Same(t, unrelated, withoutID(unrelated, "sbx-1"), "an error without the ID is kept as it is") + assert.Same(t, unrelated, withoutID(unrelated, "")) +} + +func TestSnapshotDefaults(t *testing.T) { + op := &snapshotOperation{} + require.NoError(t, op.Command().ParseFlags(nil)) + assert.Equal(t, 3, op.count) + assert.NoError(t, op.validate()) +} + +func TestRunViewSnapshotCleanup(t *testing.T) { + render := func(v runView) string { + var b strings.Builder + require.NoError(t, v.writePretty(&b)) + return b.String() + } + + clean := newRunView("run-1", "system/base", 1, 300, benchmark.Report{ + Phases: []benchmark.PhaseReport{{Phase: phaseSnapshot}}, + }) + assert.NotContains(t, render(clean), "snapshot delete") + + data, err := json.Marshal(clean) + require.NoError(t, err) + assert.Contains(t, string(data), `"leaked_snapshots":[]`) + + leaky := clean + leaky.LeakedSnapshots = []string{"bench-run-1-a", "bench-run-1-b"} + out := render(leaky) + assert.Contains(t, out, "2 snapshot(s) could not be deleted") + assert.Contains(t, out, "Delete them with: ucloud-sandbox-cli snapshot delete bench-run-1-a bench-run-1-b") + + failed := newRunView("run-1", "system/base", 1, 300, benchmark.Report{ + Phases: []benchmark.PhaseReport{{Phase: phaseSnapshot, Failed: 1}}, + }) + out = render(failed) + assert.Contains(t, out, "1 snapshot(s) failed; the service may still have taken some of them.") + assert.Contains(t, out, "snapshots whose names contain bench-run-1- in: ucloud-sandbox-cli snapshot list") + + failure := func(phase benchmark.Phase, err error) benchmark.IterationResult { + return benchmark.IterationResult{Phases: []benchmark.PhaseResult{{Phase: phase, Err: err}}} + } + copies := newRunView("run-1", "system/base", 1, 300, benchmark.Report{ + Phases: []benchmark.PhaseReport{{Phase: phaseRestore, Failed: 2}, {Phase: phaseFork, Failed: 2}}, + Iterations: []benchmark.IterationResult{ + failure(phaseRestore, errors.New("HTTP 500")), + failure(phaseRestore, notAttempted("no snapshot was taken")), + failure(phaseFork, errors.New("timeout")), + failure(phaseFork, errors.New("timeout")), + }, + }) + out = render(copies) + assert.Contains(t, out, "3 restore(s) or fork(s) failed; the service may still have started some of those sandboxes.", + "a restore that was never attempted started nothing") + assert.Contains(t, out, "Clean them up with: ucloud-sandbox-cli sandbox kill --all -m benchmark=run-1") + + notSent := newRunView("run-1", "system/base", 1, 300, benchmark.Report{ + Phases: []benchmark.PhaseReport{{Phase: phaseSnapshot}, {Phase: phaseRestore, Failed: 1}}, + Iterations: []benchmark.IterationResult{failure(phaseRestore, notAttempted("no snapshot was taken"))}, + }) + assert.NotContains(t, render(notSent), "restore(s) or fork(s) failed") +} + +func TestWriteHeaderSnapshots(t *testing.T) { + op := &runOptions{template: "system/base", count: 3, concurrency: 1} + + var b strings.Builder + op.writeHeader(&b, runSpec{name: "snapshot", snapshots: true}, "run-1") + + assert.Equal(t, `Running snapshot benchmark run-1 + Template: system/base + Iterations: 3 (concurrency 1) + Sandbox tag: benchmark=run-1 + Snapshots: named bench-run-1- + Cleanup: ucloud-sandbox-cli sandbox kill --all -m benchmark=run-1 + ucloud-sandbox-cli snapshot delete + +`, b.String()) +} diff --git a/cmd/benchmark/view.go b/cmd/benchmark/view.go new file mode 100644 index 0000000..1705e7b --- /dev/null +++ b/cmd/benchmark/view.go @@ -0,0 +1,408 @@ +package benchmark + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "slices" + "strconv" + "strings" + "time" + + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" + "github.com/ucloud/ucloud-sandbox-cli/internal/table" +) + +// runView is the output of a benchmark run, shaped for JSON with durations in +// milliseconds. +type runView struct { + RunID string `json:"run_id"` + Template string `json:"template"` + Concurrency int `json:"concurrency"` + SandboxTimeoutSec int32 `json:"sandbox_timeout_sec"` + + Requested int `json:"requested"` + Started int `json:"started"` + Succeeded int `json:"succeeded"` + Failed int `json:"failed"` + Interrupted bool `json:"interrupted"` + + ElapsedMs float64 `json:"elapsed_ms"` + Rate float64 `json:"rate_per_sec"` + + Phases []phaseView `json:"phases"` + Errors []errorView `json:"errors"` + Leaked []string `json:"leaked"` + + // LeakedSnapshots names the snapshots the run took but could not delete. + // The names, not the IDs, are what `snapshot delete` deletes them by. + LeakedSnapshots []string `json:"leaked_snapshots"` + + // LeftRunning counts the sandboxes the run left running on purpose, to be + // reclaimed by their timeout. + LeftRunning int `json:"left_running"` + + // Iterations is the raw sample of every iteration that ran. It is only + // written as JSON. + Iterations []iterationView `json:"iterations"` + + // breakdown shows every phase's full latency in the pretty table, with its + // connect and service rows under it, rather than its service time alone. + breakdown bool + + // copyStartsFailed counts the restores and forks that failed after their + // request was sent, and so may have started a sandbox all the same. + copyStartsFailed int +} + +// phaseView is the statistics of one phase. Its latencies cover the whole +// phase; Connect and Service split every sample into the time spent obtaining +// HTTP connections and the rest. +type phaseView struct { + Phase string `json:"phase"` + Succeeded int `json:"succeeded"` + Failed int `json:"failed"` + latencyView + Connect latencyView `json:"connect"` + Service latencyView `json:"service"` +} + +type latencyView struct { + AvgMs float64 `json:"avg_ms"` + MinMs float64 `json:"min_ms"` + P50Ms float64 `json:"p50_ms"` + P95Ms float64 `json:"p95_ms"` + P99Ms float64 `json:"p99_ms"` + MaxMs float64 `json:"max_ms"` +} + +func newLatencyView(s benchmark.Stats) latencyView { + return latencyView{ + AvgMs: ms(s.Avg), + MinMs: ms(s.Min), + P50Ms: ms(s.P50), + P95Ms: ms(s.P95), + P99Ms: ms(s.P99), + MaxMs: ms(s.Max), + } +} + +// iterationView is the outcome of one iteration. +type iterationView struct { + Seq int `json:"seq"` + SandboxID string `json:"sandbox_id"` + StartOffsetMs float64 `json:"start_offset_ms"` + Succeeded bool `json:"succeeded"` + + Phases []iterationPhaseView `json:"phases"` + Leaked []string `json:"leaked"` +} + +// iterationPhaseView is one phase of an iteration: its latencies when it +// succeeded, its error when it failed. The latencies are pointers so a zero +// connect time is still written. +type iterationPhaseView struct { + Phase string `json:"phase"` + DurationMs *float64 `json:"duration_ms,omitempty"` + ConnectMs *float64 `json:"connect_ms,omitempty"` + Error string `json:"error,omitempty"` +} + +func newIterationView(r benchmark.IterationResult) iterationView { + v := iterationView{ + Seq: r.Seq, + SandboxID: r.SandboxID, + StartOffsetMs: ms(r.Start), + Succeeded: r.Succeeded(), + Phases: make([]iterationPhaseView, 0, len(r.Phases)), + Leaked: append([]string{}, r.Leaked...), + } + + for _, p := range r.Phases { + if p.Err != nil { + // Collapse whitespace so the message fits on one line. Unlike the + // grouped errors, the sandbox ID is kept: it is this iteration's. + v.Phases = append(v.Phases, iterationPhaseView{ + Phase: string(p.Phase), + Error: strings.Join(strings.Fields(p.Err.Error()), " "), + }) + continue + } + duration, connect := ms(p.Duration), ms(p.Connect) + v.Phases = append(v.Phases, iterationPhaseView{ + Phase: string(p.Phase), + DurationMs: &duration, + ConnectMs: &connect, + }) + } + + return v +} + +type errorView struct { + Phase string `json:"phase"` + Count int `json:"count"` + Message string `json:"message"` +} + +func newRunView(runID, template string, concurrency int, timeoutSec int32, r benchmark.Report) runView { + v := runView{ + RunID: runID, + Template: template, + Concurrency: concurrency, + SandboxTimeoutSec: timeoutSec, + Requested: r.Requested, + Started: r.Started, + Succeeded: r.Succeeded, + Failed: r.Failed, + Interrupted: r.Interrupted, + ElapsedMs: ms(r.Elapsed), + Rate: r.Rate(), + Phases: make([]phaseView, 0, len(r.Phases)), + Errors: make([]errorView, 0, len(r.Errors)), + Leaked: append([]string{}, r.Leaked...), + LeakedSnapshots: []string{}, + Iterations: make([]iterationView, 0, len(r.Iterations)), + } + + for _, p := range r.Phases { + v.Phases = append(v.Phases, phaseView{ + Phase: string(p.Phase), + Succeeded: p.Stats.Count, + Failed: p.Failed, + latencyView: newLatencyView(p.Stats), + Connect: newLatencyView(p.Connect), + Service: newLatencyView(p.Service), + }) + } + + for _, e := range r.Errors { + v.Errors = append(v.Errors, errorView{Phase: string(e.Phase), Count: e.Count, Message: e.Message}) + } + + for _, it := range r.Iterations { + v.Iterations = append(v.Iterations, newIterationView(it)) + } + + v.copyStartsFailed = failedRequests(r.Iterations, phaseRestore, phaseFork) + + return v +} + +// ms converts d to milliseconds, rounded to the microsecond. +func ms(d time.Duration) float64 { + return float64(d.Round(time.Microsecond)) / float64(time.Millisecond) +} + +// phaseRow is one row of the latency table. The counts are strings so the +// breakdown rows under a phase can leave them blank. +type phaseRow struct { + Phase string `table_field:"Phase"` + Succeeded string `table_field:"Succeeded"` + Failed string `table_field:"Failed"` + Avg string `table_field:"Avg"` + Min string `table_field:"Min"` + P50 string `table_field:"P50"` + P95 string `table_field:"P95"` + P99 string `table_field:"P99"` + Max string `table_field:"Max"` +} + +// withLatency fills in the latency columns of the row. +func (r phaseRow) withLatency(l latencyView) phaseRow { + r.Avg, r.Min = formatMs(l.AvgMs), formatMs(l.MinMs) + r.P50, r.P95, r.P99, r.Max = formatMs(l.P50Ms), formatMs(l.P95Ms), formatMs(l.P99Ms), formatMs(l.MaxMs) + return r +} + +// errorRow is one row of the error table. +type errorRow struct { + Phase string `table_field:"Phase"` + Count int `table_field:"Count"` + Message string `table_field:"Message"` +} + +// checkReportFile checks that path can be written, creating it if it does not +// exist. It runs before a benchmark starts, so a wrong path fails in the first +// second instead of after the whole run. +func checkReportFile(path string) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644) + if err != nil { + return fmt.Errorf("report file: %w", err) + } + return f.Close() +} + +// writeJSONFile writes the view to path as the same JSON document --format +// json prints, so a run can show its table and keep its samples at once. +func (v runView) writeJSONFile(path string) error { + data, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + if err := os.WriteFile(path, append(data, '\n'), 0o644); err != nil { + return fmt.Errorf("write report: %w", err) + } + return nil +} + +// writePretty writes the view as a summary followed by ASCII tables. +func (v runView) writePretty(w io.Writer) error { + status := "completed" + if v.Interrupted { + status = "interrupted" + } + + fmt.Fprintf(w, "Benchmark %s %s: template %s, concurrency %d\n", v.RunID, status, v.Template, v.Concurrency) + fmt.Fprintf(w, "Iterations: %d/%d started, %d succeeded, %d failed\n", v.Started, v.Requested, v.Succeeded, v.Failed) + fmt.Fprintf(w, "Elapsed: %s, rate: %s sandbox/s\n\n", + formatMs(v.ElapsedMs), strconv.FormatFloat(v.Rate, 'f', 2, 64)) + + // The JSON output reports the full latency under the same names, so say + // which one the table shows. + if v.breakdown { + fmt.Fprintln(w, "Latency per phase, split into connection setup (connect) and service time (service):") + } else { + fmt.Fprintln(w, "Service time per phase, excluding connection setup (DNS, dial, TLS); --breakdown shows the full latency:") + } + + // By default a phase shows its service time: its latency less the time + // spent obtaining HTTP connections (DNS, dial, TLS), which depends on the + // client's network more than on the service. The breakdown shows the full + // latency, followed by both parts. + rows := make([]phaseRow, 0, 3*len(v.Phases)) + for _, p := range v.Phases { + row := phaseRow{Phase: p.Phase, Succeeded: strconv.Itoa(p.Succeeded), Failed: strconv.Itoa(p.Failed)} + if p.Succeeded == 0 { + rows = append(rows, row) + continue + } + if !v.breakdown { + rows = append(rows, row.withLatency(p.Service)) + continue + } + rows = append(rows, + row.withLatency(p.latencyView), + phaseRow{Phase: " connect"}.withLatency(p.Connect), + phaseRow{Phase: " service"}.withLatency(p.Service), + ) + } + + out, err := table.RenderPlain(rows) + if err != nil { + return err + } + fmt.Fprint(w, out) + + if len(v.Errors) > 0 { + errs := make([]errorRow, 0, len(v.Errors)) + for _, e := range v.Errors { + errs = append(errs, errorRow(e)) + } + + out, err := table.RenderPlain(errs) + if err != nil { + return err + } + fmt.Fprint(w, "\nErrors:\n"+out) + } + + v.writeCleanup(w) + v.writeSnapshotCleanup(w) + + return nil +} + +// writeCleanup tells the user about every sandbox the run may have left +// behind, followed by the one command that kills them all. +func (v runView) writeCleanup(w io.Writer) { + hint := "" + + if len(v.Leaked) > 0 { + fmt.Fprintf(w, "\n%d sandbox(es) could not be killed and live until their timeout:\n", len(v.Leaked)) + for _, id := range v.Leaked { + fmt.Fprintf(w, " %s\n", id) + } + // Killing by ID also reaches a sandbox without the run's tag, which + // a fork may be. + fmt.Fprintf(w, "Kill them with: ucloud-sandbox-cli sandbox kill %s\n", strings.Join(v.Leaked, " ")) + hint = "Clean up the rest of the run with" + } + + // A create that failed on the client, a timeout say, may still have + // started its sandbox on the service, where nothing here can see it. + if failed := v.phaseFailed(benchmark.PhaseCreate); failed > 0 { + fmt.Fprintf(w, "\n%d create(s) failed; the service may still have started some of those sandboxes.\n", failed) + hint = "Clean them up with" + } + + // Restoring and forking start sandboxes too, the same way. + if failed := v.copyStartsFailed; failed > 0 { + fmt.Fprintf(w, "\n%d restore(s) or fork(s) failed; the service may still have started some of those sandboxes.\n", failed) + hint = "Clean them up with" + } + + if v.LeftRunning > 0 { + fmt.Fprintf(w, "\n%d sandbox(es) left running, reclaimed after their %s timeout.\n", + v.LeftRunning, time.Duration(v.SandboxTimeoutSec)*time.Second) + if hint == "" { + hint = "Kill them sooner with" + } + } + + if hint != "" { + fmt.Fprintf(w, "%s: %s\n", hint, cleanupCommand(v.RunID)) + } +} + +// phaseFailed returns the number of iterations in which phase failed. +func (v runView) phaseFailed(phase benchmark.Phase) int { + for _, p := range v.Phases { + if p.Phase == string(phase) { + return p.Failed + } + } + return 0 +} + +// failedRequests counts the failures of phases that got as far as sending +// their request. A step left out because one before it failed sent nothing, +// so it cannot have started anything on the service. +func failedRequests(iterations []benchmark.IterationResult, phases ...benchmark.Phase) int { + n := 0 + for _, it := range iterations { + for _, p := range it.Phases { + if p.Err != nil && slices.Contains(phases, p.Phase) && !errors.Is(p.Err, errNotAttempted) { + n++ + } + } + } + return n +} + +// writeSnapshotCleanup tells the user about the snapshots the run may have +// left behind. Unlike sandboxes, they never expire. +func (v runView) writeSnapshotCleanup(w io.Writer) { + if len(v.LeakedSnapshots) > 0 { + fmt.Fprintf(w, "\n%d snapshot(s) could not be deleted and are kept until deleted:\n", len(v.LeakedSnapshots)) + for _, id := range v.LeakedSnapshots { + fmt.Fprintf(w, " %s\n", id) + } + fmt.Fprintf(w, "Delete them with: ucloud-sandbox-cli snapshot delete %s\n", strings.Join(v.LeakedSnapshots, " ")) + } + + // Like a create, a snapshot that failed on the client may still have been + // taken on the service. + if failed := v.phaseFailed(phaseSnapshot); failed > 0 { + fmt.Fprintf(w, "\n%d snapshot(s) failed; the service may still have taken some of them.\n", failed) + fmt.Fprintf(w, "Look for snapshots whose names contain %s in: ucloud-sandbox-cli snapshot list\n", snapshotNamePrefix(v.RunID)) + } +} + +// formatMs renders a millisecond value as a duration rounded to the +// millisecond, e.g. "523ms" or "1.234s". +func formatMs(v float64) string { + return time.Duration(v * float64(time.Millisecond)).Round(time.Millisecond).String() +} diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go new file mode 100644 index 0000000..83c2cbf --- /dev/null +++ b/internal/benchmark/benchmark_test.go @@ -0,0 +1,739 @@ +package benchmark + +import ( + "context" + "errors" + "fmt" + "net/http/httptrace" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSummarizeEmpty(t *testing.T) { + assert.Equal(t, Stats{}, Summarize(nil)) +} + +func TestSummarizeSingleSample(t *testing.T) { + s := Summarize([]time.Duration{5 * time.Millisecond}) + + assert.Equal(t, 1, s.Count) + for _, d := range []time.Duration{s.Avg, s.Min, s.P50, s.P95, s.P99, s.Max} { + assert.Equal(t, 5*time.Millisecond, d) + } +} + +func TestSummarizeNearestRank(t *testing.T) { + // 100..1 ms in reverse order, so sorting is exercised. + samples := make([]time.Duration, 0, 100) + for i := 100; i >= 1; i-- { + samples = append(samples, time.Duration(i)*time.Millisecond) + } + + s := Summarize(samples) + + assert.Equal(t, 100, s.Count) + assert.Equal(t, 1*time.Millisecond, s.Min) + assert.Equal(t, 100*time.Millisecond, s.Max) + assert.Equal(t, 50500*time.Microsecond, s.Avg) + assert.Equal(t, 50*time.Millisecond, s.P50) + assert.Equal(t, 95*time.Millisecond, s.P95) + assert.Equal(t, 99*time.Millisecond, s.P99) + + assert.Equal(t, 100*time.Millisecond, samples[0], "input is left unsorted") +} + +func TestSummarizeSmallSetPercentiles(t *testing.T) { + s := Summarize([]time.Duration{1, 2, 3}) + + assert.Equal(t, time.Duration(2), s.P50) + assert.Equal(t, time.Duration(3), s.P95) + assert.Equal(t, time.Duration(3), s.P99) +} + +// fakeSandbox is a Sandbox whose phases fail as configured. +type fakeSandbox struct { + id string + execErr error + killErr error + + execCalls atomic.Int32 + killCalls atomic.Int32 +} + +func (f *fakeSandbox) ID() string { return f.id } + +func (f *fakeSandbox) Exec(context.Context) error { + f.execCalls.Add(1) + return f.execErr +} + +func (f *fakeSandbox) Kill(context.Context) error { + f.killCalls.Add(1) + return f.killErr +} + +// fakeService hands out fakeSandboxs and records them. +type fakeService struct { + mu sync.Mutex + sandboxes []*fakeSandbox + created atomic.Int32 + + // configure, when set, decides the behavior of the n-th (0-based) create. + configure func(n int, sbx *fakeSandbox) error +} + +func (s *fakeService) create(context.Context) (*fakeSandbox, error) { + n := int(s.created.Add(1)) - 1 + sbx := &fakeSandbox{id: fmt.Sprintf("sbx-%03d", n)} + + if s.configure != nil { + if err := s.configure(n, sbx); err != nil { + return nil, err + } + } + + s.mu.Lock() + s.sandboxes = append(s.sandboxes, sbx) + s.mu.Unlock() + + return sbx, nil +} + +// execer is a sandbox with an exec phase of its own. +type execer interface { + Sandbox + Exec(ctx context.Context) error +} + +// execSteps returns the single exec step of a lifecycle run. +func execSteps[S execer]() []Step[S] { + return []Step[S]{{ + Phase: PhaseExec, + Run: func(ctx context.Context, sbx S) error { return sbx.Exec(ctx) }, + }} +} + +func phaseReport(t *testing.T, r Report, phase Phase) PhaseReport { + t.Helper() + for _, p := range r.Phases { + if p.Phase == phase { + return p + } + } + require.Failf(t, "phase missing", "phase %q not in report", phase) + return PhaseReport{} +} + +func TestRunAllSucceed(t *testing.T) { + svc := &fakeService{} + + var calls []Progress + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Steps: execSteps[*fakeSandbox](), + Count: 20, + Concurrency: 4, + OnIteration: func(p Progress) { calls = append(calls, p) }, + }) + + assert.Equal(t, 20, report.Requested) + assert.Equal(t, 20, report.Started) + assert.Equal(t, 20, report.Succeeded) + assert.Equal(t, 0, report.Failed) + assert.False(t, report.Interrupted) + assert.Empty(t, report.Errors) + assert.Empty(t, report.Leaked) + + var phases []Phase + for _, p := range report.Phases { + phases = append(phases, p.Phase) + assert.Equal(t, 20, p.Stats.Count, "phase %s", p.Phase) + assert.Equal(t, 0, p.Failed, "phase %s", p.Phase) + } + assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseKill, PhaseTotal}, phases) + + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 1, sbx.execCalls.Load()) + assert.EqualValues(t, 1, sbx.killCalls.Load()) + } + + require.Len(t, calls, 20) + assert.Equal(t, Progress{Done: 20, Total: 20, Succeeded: 20}, calls[19]) +} + +func TestRunSkipExec(t *testing.T) { + svc := &fakeService{} + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 3, + Concurrency: 1, + }) + + var phases []Phase + for _, p := range report.Phases { + phases = append(phases, p.Phase) + } + assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, phases) + + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 0, sbx.execCalls.Load()) + assert.EqualValues(t, 1, sbx.killCalls.Load()) + } +} + +func TestRunFailures(t *testing.T) { + svc := &fakeService{ + configure: func(n int, sbx *fakeSandbox) error { + switch n % 5 { + case 1: + return errors.New("quota exceeded") + case 2: + sbx.execErr = errors.New("exit status 1") + case 3: + sbx.killErr = errors.New("kill timeout") + case 4: + sbx.killErr = fmt.Errorf("wrapped: %w", ErrSandboxNotFound) + } + return nil + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Steps: execSteps[*fakeSandbox](), + Count: 10, + Concurrency: 1, + }) + + assert.Equal(t, 10, report.Started) + assert.Equal(t, 2, report.Succeeded) + assert.Equal(t, 8, report.Failed) + + create := phaseReport(t, report, PhaseCreate) + assert.Equal(t, 8, create.Stats.Count) + assert.Equal(t, 2, create.Failed) + + exec := phaseReport(t, report, PhaseExec) + assert.Equal(t, 6, exec.Stats.Count) + assert.Equal(t, 2, exec.Failed) + + kill := phaseReport(t, report, PhaseKill) + assert.Equal(t, 4, kill.Stats.Count) + assert.Equal(t, 4, kill.Failed) + + total := phaseReport(t, report, PhaseTotal) + assert.Equal(t, 2, total.Stats.Count) + assert.Equal(t, 8, total.Failed) + + // A failed exec still kills the sandbox. + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 1, sbx.killCalls.Load(), sbx.id) + } + + // Only the sandbox whose kill failed outright is leaked; one that is + // the service reports as not found is not. + assert.Equal(t, []string{"sbx-003", "sbx-008"}, report.Leaked) + + assert.ElementsMatch(t, []ErrorCount{ + {Phase: PhaseCreate, Message: "quota exceeded", Count: 2}, + {Phase: PhaseExec, Message: "exit status 1", Count: 2}, + {Phase: PhaseKill, Message: "kill timeout", Count: 2}, + {Phase: PhaseKill, Message: "wrapped: sandbox not found (HTTP 404)", Count: 2}, + }, report.Errors) +} + +func TestRunErrorsSortedByCount(t *testing.T) { + svc := &fakeService{ + configure: func(n int, _ *fakeSandbox) error { + if n == 0 { + return errors.New("rare") + } + return errors.New("common") + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{Steps: execSteps[*fakeSandbox](), Count: 4, Concurrency: 1}) + + require.Len(t, report.Errors, 2) + assert.Equal(t, ErrorCount{Phase: PhaseCreate, Message: "common", Count: 3}, report.Errors[0]) + assert.Equal(t, ErrorCount{Phase: PhaseCreate, Message: "rare", Count: 1}, report.Errors[1]) +} + +func TestRunRespectsConcurrency(t *testing.T) { + var inFlight, peak atomic.Int32 + + create := func(context.Context) (*fakeSandbox, error) { + n := inFlight.Add(1) + for { + p := peak.Load() + if n <= p || peak.CompareAndSwap(p, n) { + break + } + } + time.Sleep(5 * time.Millisecond) + inFlight.Add(-1) + return &fakeSandbox{id: "sbx"}, nil + } + + report := Run(context.Background(), create, Options[*fakeSandbox]{Steps: execSteps[*fakeSandbox](), Count: 30, Concurrency: 3}) + + assert.Equal(t, 30, report.Succeeded) + assert.LessOrEqual(t, peak.Load(), int32(3)) + assert.Greater(t, peak.Load(), int32(1), "iterations run concurrently") +} + +func TestRunCancelStopsNewIterationsAndCleansUp(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + svc := &fakeService{} + release := make(chan struct{}) + + create := func(c context.Context) (*fakeSandbox, error) { + sbx, err := svc.create(c) + if svc.created.Load() == 2 { + // The second iteration is in flight when the run is cancelled. + cancel() + <-release + } + return sbx, err + } + + go func() { + <-ctx.Done() + close(release) + }() + + report := Run(ctx, create, Options[*fakeSandbox]{Steps: execSteps[*fakeSandbox](), Count: 100, Concurrency: 1}) + + assert.True(t, report.Interrupted) + assert.Equal(t, 100, report.Requested) + assert.Equal(t, 2, report.Started) + assert.Equal(t, 2, report.Succeeded, "the in-flight iteration completes on a detached context") + assert.Len(t, report.Iterations, 2, "iterations that never started have no result") + + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 1, sbx.killCalls.Load(), sbx.id) + } +} + +func TestRunZeroCount(t *testing.T) { + svc := &fakeService{} + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{Count: 0, Concurrency: 5}) + + assert.Equal(t, 0, report.Started) + assert.EqualValues(t, 0, svc.created.Load()) +} + +func TestReportRate(t *testing.T) { + assert.InDelta(t, 2.5, Report{Succeeded: 5, Elapsed: 2 * time.Second}.Rate(), 1e-9) + assert.Zero(t, Report{Succeeded: 5}.Rate()) +} + +// simulateConnect fires the httptrace hooks of ctx as an HTTP request taking d +// to obtain its connection would. +func simulateConnect(ctx context.Context, d time.Duration) { + trace := httptrace.ContextClientTrace(ctx) + if trace == nil { + return + } + trace.GetConn("example.com:443") + time.Sleep(d) + trace.GotConn(httptrace.GotConnInfo{}) +} + +func TestConnTraceSumsSequentialRequests(t *testing.T) { + ctx, trace := withConnTrace(context.Background()) + + simulateConnect(ctx, 5*time.Millisecond) + simulateConnect(ctx, 5*time.Millisecond) + + assert.GreaterOrEqual(t, trace.Total(), 10*time.Millisecond) +} + +func TestConnTraceIgnoresUnpairedGotConn(t *testing.T) { + ctx, trace := withConnTrace(context.Background()) + + httptrace.ContextClientTrace(ctx).GotConn(httptrace.GotConnInfo{}) + + assert.Zero(t, trace.Total()) +} + +// connectingSandbox spends connect obtaining a connection, then work +// responding, in every phase. +type connectingSandbox struct { + connect, work time.Duration +} + +func (i connectingSandbox) phase(ctx context.Context) error { + simulateConnect(ctx, i.connect) + time.Sleep(i.work) + return nil +} + +func (i connectingSandbox) ID() string { return "sbx" } +func (i connectingSandbox) Exec(ctx context.Context) error { return i.phase(ctx) } +func (i connectingSandbox) Kill(ctx context.Context) error { return i.phase(ctx) } + +func TestRunSplitsConnectFromService(t *testing.T) { + const connect, work = 20 * time.Millisecond, 10 * time.Millisecond + sbx := connectingSandbox{connect: connect, work: work} + + create := func(ctx context.Context) (connectingSandbox, error) { + return sbx, sbx.phase(ctx) + } + + report := Run(context.Background(), create, Options[connectingSandbox]{ + Steps: execSteps[connectingSandbox](), Count: 2, Concurrency: 1, + }) + require.Equal(t, 2, report.Succeeded) + + for _, phase := range []Phase{PhaseCreate, PhaseExec, PhaseKill} { + p := phaseReport(t, report, phase) + assert.Equal(t, 2, p.Connect.Count, phase) + assert.GreaterOrEqual(t, p.Connect.Min, connect, phase) + assert.GreaterOrEqual(t, p.Service.Min, work, phase) + assert.Less(t, p.Service.Max, connect, "%s: connection setup is not counted as service time", phase) + } + + total := phaseReport(t, report, PhaseTotal) + assert.GreaterOrEqual(t, total.Connect.Min, 3*connect, "total sums the connection setup of every phase") + assert.GreaterOrEqual(t, total.Service.Min, 3*work) +} + +func TestRunFailedPhaseRecordsNoConnect(t *testing.T) { + svc := &fakeService{ + configure: func(_ int, sbx *fakeSandbox) error { + sbx.execErr = errors.New("boom") + return nil + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{Steps: execSteps[*fakeSandbox](), Count: 1, Concurrency: 1}) + + exec := phaseReport(t, report, PhaseExec) + assert.Zero(t, exec.Connect.Count) + assert.Zero(t, exec.Service.Count) + assert.Equal(t, 1, phaseReport(t, report, PhaseCreate).Connect.Count) +} + +func TestRunCreateOnly(t *testing.T) { + svc := &fakeService{ + configure: func(n int, _ *fakeSandbox) error { + if n == 0 { + return errors.New("quota exceeded") + } + return nil + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 4, + Concurrency: 2, + SkipKill: true, + }) + + require.Len(t, report.Phases, 1, "a lone phase has no total") + create := report.Phases[0] + assert.Equal(t, PhaseCreate, create.Phase) + assert.Equal(t, 3, create.Stats.Count) + assert.Equal(t, 1, create.Failed) + + assert.Equal(t, 3, report.Succeeded) + assert.Equal(t, 1, report.Failed) + assert.Empty(t, report.Leaked, "sandboxes left running on purpose are not leaks") + + require.Len(t, svc.sandboxes, 3) + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 0, sbx.execCalls.Load(), sbx.id) + assert.EqualValues(t, 0, sbx.killCalls.Load(), sbx.id) + } +} + +func TestOptionsPhases(t *testing.T) { + exec := execSteps[*fakeSandbox]() + type opts = Options[*fakeSandbox] + + assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseKill, PhaseTotal}, opts{Steps: exec}.phases()) + assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, opts{}.phases()) + assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseTotal}, opts{Steps: exec, SkipKill: true}.phases()) + assert.Equal(t, []Phase{PhaseCreate}, opts{SkipKill: true}.phases()) + + steps := []Step[*fakeSandbox]{{Phase: "a"}, {Phase: "b"}} + assert.Equal(t, []Phase{PhaseCreate, "a", "b", PhaseKill, PhaseTotal}, opts{Steps: steps}.phases()) +} + +func TestNormalizeMessage(t *testing.T) { + assert.Equal(t, + "command exited with code 127: bash: nope: command not found", + normalizeMessage(errors.New("command exited with code 127: bash: nope: command not found\n"), "sbx-1")) + assert.Equal(t, + "line one line two", + normalizeMessage(errors.New(" line one\n\tline two\r\n"), "")) + assert.Equal(t, + "dial tcp: i/o timeout", + normalizeMessage(errors.New(`Post "https://49983-ibx7k2.example.com/process.Process/Start": dial tcp: i/o timeout`), "ibx7k2"), + "the request URL is dropped") + // Delete, which kill and snapshot-delete use, is dropped too. + assert.Equal(t, + "context deadline exceeded", + normalizeMessage(errors.New(`Delete "https://api.cn-sh.sandbox.ucloudai.com/sandboxes/sbx": context deadline exceeded`), "")) + + // The URL is dropped inside a wrapped message too, which keeps its prefix + // and its cause. + assert.Equal(t, + "write /tmp/ucloud-sandbox-health: net/http: TLS handshake timeout", + normalizeMessage(fmt.Errorf("write %s: %w", "/tmp/ucloud-sandbox-health", + errors.New(`Post "https://49983-ibx7k2.cn-sh.sandbox.ucloudai.com/files?path=%2Ftmp%2Fucloud-sandbox-health": net/http: TLS handshake timeout`)), "ibx7k2")) +} + +func TestRunGroupsErrorsAcrossSandboxes(t *testing.T) { + svc := &fakeService{ + configure: func(n int, sbx *fakeSandbox) error { + // Every exec fails with a message naming its own sandbox and + // spanning several lines. + sbx.execErr = fmt.Errorf("dial https://49983-%s.example.com: refused\nretry later\n", sbx.id) + return nil + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{Steps: execSteps[*fakeSandbox](), Count: 5, Concurrency: 2}) + + require.Len(t, report.Errors, 1) + assert.Equal(t, ErrorCount{ + Phase: PhaseExec, + Message: "dial https://49983-.example.com: refused retry later", + Count: 5, + }, report.Errors[0]) +} + +func TestRunStepsRunInOrderPastFailures(t *testing.T) { + var mu sync.Mutex + var order []Phase + step := func(phase Phase, err error) Step[*fakeSandbox] { + return Step[*fakeSandbox]{Phase: phase, Run: func(context.Context, *fakeSandbox) error { + mu.Lock() + order = append(order, phase) + mu.Unlock() + return err + }} + } + + svc := &fakeService{} + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{ + step("internet", errors.New("could not resolve host")), + step("filesystem", nil), + }, + }) + + assert.Equal(t, []Phase{"internet", "filesystem"}, order, "a failed step does not stop the next") + assert.Equal(t, 1, phaseReport(t, report, "internet").Failed) + assert.Equal(t, 1, phaseReport(t, report, "filesystem").Stats.Count) + assert.EqualValues(t, 1, svc.sandboxes[0].killCalls.Load()) +} + +func TestRunUntimedStep(t *testing.T) { + var order []Phase + record := func(phase Phase, sleep time.Duration, err error) Step[*fakeSandbox] { + return Step[*fakeSandbox]{Phase: phase, Run: func(context.Context, *fakeSandbox) error { + order = append(order, phase) + time.Sleep(sleep) + return err + }} + } + cleanup := record("cleanup", 20*time.Millisecond, nil) + cleanup.Untimed = true + + svc := &fakeService{} + opts := Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{record("work", 0, nil), cleanup, record("after", 0, nil)}, + } + report := Run(context.Background(), svc.create, opts) + + assert.Equal(t, []Phase{"work", "cleanup", "after"}, order, "untimed steps run in their place") + assert.Equal(t, []Phase{PhaseCreate, "work", "after", PhaseKill, PhaseTotal}, opts.phases(), "and get no row") + for _, p := range report.Phases { + assert.NotEqual(t, Phase("cleanup"), p.Phase) + } + assert.Equal(t, 1, report.Succeeded) + assert.Less(t, phaseReport(t, report, "after").Stats.Max, 20*time.Millisecond) +} + +func TestRunUntimedStepFailureFailsIterationAndLeaks(t *testing.T) { + svc := &fakeService{} + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{{ + Phase: "cleanup", + Untimed: true, + Run: func(context.Context, *fakeSandbox) error { + return &LeakedError{IDs: []string{"sbx-fork"}, Err: errors.New("HTTP 500")} + }, + }}, + }) + + assert.Equal(t, 0, report.Succeeded, "a leak is a failure") + assert.Equal(t, 1, report.Failed) + assert.Equal(t, []string{"sbx-fork"}, report.Leaked) + assert.Equal(t, []ErrorCount{{Phase: "cleanup", Message: "could not kill 1 sandbox(es): HTTP 500", Count: 1}}, report.Errors) + assert.EqualValues(t, 1, svc.sandboxes[0].killCalls.Load(), "the sandbox is still killed") +} + +func TestRunLeaksBothStepAndKillFailures(t *testing.T) { + svc := &fakeService{configure: func(_ int, sbx *fakeSandbox) error { + sbx.killErr = errors.New("kill timeout") + return nil + }} + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{{Phase: "cleanup", Untimed: true, Run: func(context.Context, *fakeSandbox) error { + return &LeakedError{IDs: []string{"sbx-fork"}, Err: errors.New("HTTP 500")} + }}}, + }) + + assert.Equal(t, []string{"sbx-000", "sbx-fork"}, report.Leaked) +} + +// phaseNames returns the phases of an iteration in the order they ran, each +// suffixed with "!" when it failed. +func phaseNames(r IterationResult) []string { + names := make([]string, 0, len(r.Phases)) + for _, p := range r.Phases { + if p.Err != nil { + names = append(names, string(p.Phase)+"!") + } else { + names = append(names, string(p.Phase)) + } + } + return names +} + +func TestRunRecordsIterations(t *testing.T) { + svc := &fakeService{ + configure: func(n int, sbx *fakeSandbox) error { + switch n { + case 1: + return errors.New("quota exceeded") + case 2: + sbx.execErr = errors.New("exit status 1") + case 3: + sbx.killErr = errors.New("kill timeout") + } + return nil + }, + } + + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Steps: execSteps[*fakeSandbox](), + Count: 4, + Concurrency: 1, + }) + + require.Len(t, report.Iterations, 4) + + var prevStart time.Duration + for i, it := range report.Iterations { + assert.Equal(t, i+1, it.Seq) + assert.GreaterOrEqual(t, it.Start, prevStart, "a serial run starts its iterations in order") + prevStart = it.Start + } + + ok := report.Iterations[0] + assert.True(t, ok.Succeeded()) + assert.Equal(t, "sbx-000", ok.SandboxID) + assert.Equal(t, []string{"create", "exec", "kill", "total"}, phaseNames(ok)) + total := ok.Phases[3] + assert.GreaterOrEqual(t, total.Duration, ok.Phases[0].Duration+ok.Phases[1].Duration+ok.Phases[2].Duration) + + createFailed := report.Iterations[1] + assert.False(t, createFailed.Succeeded()) + assert.Empty(t, createFailed.SandboxID) + assert.Equal(t, []string{"create!"}, phaseNames(createFailed), "no phase runs after a failed create") + assert.EqualError(t, createFailed.Phases[0].Err, "quota exceeded") + assert.Zero(t, createFailed.Phases[0].Duration) + + execFailed := report.Iterations[2] + assert.Equal(t, []string{"create", "exec!", "kill"}, phaseNames(execFailed), "a failed iteration has no total") + + killFailed := report.Iterations[3] + assert.Equal(t, []string{"create", "exec", "kill!"}, phaseNames(killFailed)) + assert.Equal(t, "sbx-003", killFailed.SandboxID) + assert.Equal(t, []string{"sbx-003"}, killFailed.Leaked) +} + +func TestRunOrdersIterationsBySeq(t *testing.T) { + var n atomic.Int32 + create := func(context.Context) (*fakeSandbox, error) { + // Later iterations finish first, so completion order is not seq order. + time.Sleep(time.Duration(10-n.Add(1)%10) * time.Millisecond) + return &fakeSandbox{id: "sbx"}, nil + } + + report := Run(context.Background(), create, Options[*fakeSandbox]{Count: 20, Concurrency: 4}) + + require.Len(t, report.Iterations, 20) + for i, it := range report.Iterations { + assert.Equal(t, i+1, it.Seq) + } +} + +func TestRunRecordsUntimedStepOnlyWhenItFails(t *testing.T) { + step := func(phase Phase, untimed bool, err error) Step[*fakeSandbox] { + return Step[*fakeSandbox]{Phase: phase, Untimed: untimed, Run: func(context.Context, *fakeSandbox) error { + return err + }} + } + + run := func(cleanupErr error) IterationResult { + svc := &fakeService{} + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{ + step("work", false, nil), + step("cleanup", true, cleanupErr), + step("after", false, nil), + }, + }) + require.Len(t, report.Iterations, 1) + return report.Iterations[0] + } + + assert.Equal(t, []string{"create", "work", "after", "kill", "total"}, phaseNames(run(nil))) + assert.Equal(t, []string{"create", "work", "cleanup!", "after", "kill"}, phaseNames(run(errors.New("HTTP 500"))), + "a failed untimed step shows up where it ran") +} + +func TestRunTotalCountsConnectOfUntimedSteps(t *testing.T) { + const connect = 20 * time.Millisecond + + svc := &fakeService{} + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Count: 1, + Concurrency: 1, + Steps: []Step[*fakeSandbox]{{ + Phase: "cleanup", + Untimed: true, + Run: func(ctx context.Context, _ *fakeSandbox) error { + simulateConnect(ctx, connect) + return nil + }, + }}, + }) + require.Equal(t, 1, report.Succeeded) + + total := phaseReport(t, report, PhaseTotal) + assert.GreaterOrEqual(t, total.Connect.Min, connect, "an untimed step's connection setup is not service time") + assert.Less(t, total.Service.Max, connect) +} diff --git a/internal/benchmark/conntrace.go b/internal/benchmark/conntrace.go new file mode 100644 index 0000000..5b7958a --- /dev/null +++ b/internal/benchmark/conntrace.go @@ -0,0 +1,53 @@ +package benchmark + +import ( + "context" + "net/http/httptrace" + "sync" + "time" +) + +// connTrace measures the time HTTP requests spend obtaining a connection: DNS +// lookup, dialing and the TLS handshake for a new connection, close to zero +// for a reused one. +// +// It pairs every GetConn with the GotConn that follows, so it assumes the +// requests it watches run one after another, as they do within one phase. +type connTrace struct { + mu sync.Mutex + pending time.Time + total time.Duration +} + +// withConnTrace returns a context whose HTTP requests report their connection +// setup time to the returned trace. +func withConnTrace(ctx context.Context) (context.Context, *connTrace) { + t := &connTrace{} + return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ + GetConn: func(string) { t.getConn() }, + GotConn: func(httptrace.GotConnInfo) { t.gotConn() }, + }), t +} + +func (t *connTrace) getConn() { + t.mu.Lock() + defer t.mu.Unlock() + t.pending = time.Now() +} + +func (t *connTrace) gotConn() { + t.mu.Lock() + defer t.mu.Unlock() + if t.pending.IsZero() { + return + } + t.total += time.Since(t.pending) + t.pending = time.Time{} +} + +// Total returns the connection setup time recorded so far. +func (t *connTrace) Total() time.Duration { + t.mu.Lock() + defer t.mu.Unlock() + return t.total +} diff --git a/internal/benchmark/report.go b/internal/benchmark/report.go new file mode 100644 index 0000000..aae9f3e --- /dev/null +++ b/internal/benchmark/report.go @@ -0,0 +1,177 @@ +package benchmark + +import ( + "cmp" + "regexp" + "slices" + "strings" + "time" +) + +// Report aggregates the results of a benchmark run. +type Report struct { + // Requested is the number of iterations asked for; Started is the number + // that actually ran, which is lower when the run was interrupted. + Requested int + Started int + + Succeeded int + Failed int + + Interrupted bool + Elapsed time.Duration + + // Phases holds the statistics of every timed phase, in execution order and + // followed by PhaseTotal when the run timed more than one. + Phases []PhaseReport + + // Errors groups the failures by phase and message, most frequent first. + Errors []ErrorCount + + // Leaked lists the sandboxes that were created but could not be killed. + Leaked []string + + // Iterations holds the result of every iteration that ran, ordered by + // Seq. + Iterations []IterationResult +} + +// PhaseReport is the latency statistics of one phase. Stats.Count is the +// number of times the phase succeeded. +// +// Every successful sample is split in two: Connect is the time spent +// obtaining HTTP connections (DNS, dial, TLS), and Service is the rest, the +// time the service took to respond. Each is summarized on its own, so their +// percentiles do not add up to those of Stats. +type PhaseReport struct { + Phase Phase + Failed int + Stats Stats + Connect Stats + Service Stats +} + +// ErrorCount is the number of times one error occurred in one phase. +type ErrorCount struct { + Phase Phase + Message string + Count int +} + +// Rate returns the number of successful iterations per second. +func (r Report) Rate() float64 { + if r.Elapsed <= 0 { + return 0 + } + return float64(r.Succeeded) / r.Elapsed.Seconds() +} + +func buildReport( + results []IterationResult, + requested int, + phases []Phase, + interrupted bool, + elapsed time.Duration, +) Report { + + report := Report{ + Requested: requested, + Started: len(results), + Interrupted: interrupted, + Elapsed: elapsed, + } + + samples := make(map[Phase][]time.Duration, len(phases)) + connects := make(map[Phase][]time.Duration, len(phases)) + services := make(map[Phase][]time.Duration, len(phases)) + failed := make(map[Phase]int, len(phases)) + + type errorKey struct { + phase Phase + message string + } + errorCounts := make(map[errorKey]int) + var errorOrder []errorKey + + for _, r := range results { + if r.Succeeded() { + report.Succeeded++ + } else { + report.Failed++ + failed[PhaseTotal]++ + } + + for _, p := range r.Phases { + if p.Err == nil { + samples[p.Phase] = append(samples[p.Phase], p.Duration) + connects[p.Phase] = append(connects[p.Phase], p.Connect) + services[p.Phase] = append(services[p.Phase], p.Duration-p.Connect) + continue + } + + failed[p.Phase]++ + + key := errorKey{phase: p.Phase, message: normalizeMessage(p.Err, r.SandboxID)} + if errorCounts[key] == 0 { + errorOrder = append(errorOrder, key) + } + errorCounts[key]++ + } + + report.Leaked = append(report.Leaked, r.Leaked...) + } + + for _, phase := range phases { + report.Phases = append(report.Phases, PhaseReport{ + Phase: phase, + Failed: failed[phase], + Stats: Summarize(samples[phase]), + Connect: Summarize(connects[phase]), + Service: Summarize(services[phase]), + }) + } + + for _, key := range errorOrder { + report.Errors = append(report.Errors, ErrorCount{ + Phase: key.phase, + Message: key.message, + Count: errorCounts[key], + }) + } + // Stable, so errors seen equally often keep the order they first appeared. + slices.SortStableFunc(report.Errors, func(a, b ErrorCount) int { + return cmp.Compare(b.Count, a.Count) + }) + + slices.Sort(report.Leaked) + + report.Iterations = slices.SortedFunc(slices.Values(results), func(a, b IterationResult) int { + return cmp.Compare(a.Seq, b.Seq) + }) + + return report +} + +// sandboxPlaceholder stands in for the sandbox ID in a normalized message. +const sandboxPlaceholder = "" + +// urlErrorPattern matches the request half of the message net/http puts in +// front of the error of a failed request: the verb and the quoted URL. The +// URL names the sandbox and the request, which the phase and the sandbox ID +// already tell, and its length pushes the cause off the end of the message +// column. Any verb matches, since every request the benchmark makes can fail. +var urlErrorPattern = regexp.MustCompile(`\w+ "https?://[^"]*": `) + +// normalizeMessage prepares an error message for grouping and display. The +// request URL is dropped, since it is long and says nothing the phase does +// not, the iteration's sandbox ID, which turns up in hosts such as +// "49983-.", is replaced by a placeholder so the same failure in +// different sandboxes groups together, and runs of whitespace, newlines +// included, collapse to one space so the message fits on one table row. +func normalizeMessage(err error, sandboxID string) string { + msg := urlErrorPattern.ReplaceAllString(err.Error(), "") + if sandboxID != "" { + msg = strings.ReplaceAll(msg, sandboxID, sandboxPlaceholder) + } + return strings.Join(strings.Fields(msg), " ") +} diff --git a/internal/benchmark/runner.go b/internal/benchmark/runner.go new file mode 100644 index 0000000..2e5039b --- /dev/null +++ b/internal/benchmark/runner.go @@ -0,0 +1,319 @@ +// Package benchmark measures the latency and health of sandbox operations +// under load. +// +// The runner is decoupled from the SDK: it drives Sandbox values handed out +// by a CreateFunc through a list of Steps, so the scheduling and statistics +// can be tested without a real sandbox service. +package benchmark + +import ( + "context" + "errors" + "fmt" + "sync" + "time" +) + +// Phase names one timed step of an iteration. +type Phase string + +const ( + PhaseCreate Phase = "create" + PhaseExec Phase = "exec" + PhaseKill Phase = "kill" + + // PhaseTotal spans a whole iteration and is only recorded for iterations + // in which every phase succeeded. + PhaseTotal Phase = "total" +) + +// ErrSandboxNotFound is returned by Sandbox.Kill when the service answers +// that the sandbox does not exist (HTTP 404). The kill counts as failed, but +// the sandbox is not reported as leaked. +var ErrSandboxNotFound = errors.New("sandbox not found (HTTP 404)") + +// Sandbox is the sandbox an iteration creates and works on. +type Sandbox interface { + ID() string + Kill(ctx context.Context) error +} + +// CreateFunc creates the sandbox one iteration works on. +type CreateFunc[S Sandbox] func(ctx context.Context) (S, error) + +// Step is one operation run on the sandbox between create and kill. +type Step[S Sandbox] struct { + Phase Phase + Run func(ctx context.Context, sbx S) error + + // Untimed steps do housekeeping, such as removing what earlier steps + // created. They fail the iteration like any step, but record no duration + // and get no row of their own in the report. + Untimed bool +} + +// LeakedError is returned by a step that could not kill sandboxes it was +// responsible for. Their IDs are reported as leaked. +type LeakedError struct { + IDs []string + Err error +} + +func (e *LeakedError) Error() string { + return fmt.Sprintf("could not kill %d sandbox(es): %v", len(e.IDs), e.Err) +} + +func (e *LeakedError) Unwrap() error { return e.Err } + +// Options shape a benchmark run. +type Options[S Sandbox] struct { + // Count is the number of iterations to run. + Count int + + // Concurrency is the number of iterations in flight at once. + Concurrency int + + // Steps run in order on every sandbox after it is created. A failing step + // does not stop the ones after it, so every step reports on its own. + Steps []Step[S] + + // SkipKill leaves out the kill phase: every sandbox created is left running + // until its own timeout reclaims it. + SkipKill bool + + // OnIteration, when set, is called after every finished iteration with the + // running totals. Calls are serialized. + OnIteration func(progress Progress) +} + +// phases lists the timed phases of an iteration in execution order, followed +// by PhaseTotal when there is more than one to add up. +func (o Options[S]) phases() []Phase { + phases := []Phase{PhaseCreate} + for _, step := range o.Steps { + if !step.Untimed { + phases = append(phases, step.Phase) + } + } + if !o.SkipKill { + phases = append(phases, PhaseKill) + } + if len(phases) > 1 { + phases = append(phases, PhaseTotal) + } + return phases +} + +// Progress is the running state of a benchmark, as reported to OnIteration. +type Progress struct { + Done int + Total int + Succeeded int + Failed int +} + +// PhaseResult is the outcome of one phase of an iteration. +type PhaseResult struct { + Phase Phase + + // Duration is the time the phase took, and Connect the part of it spent + // obtaining HTTP connections (DNS, dial, TLS); the rest is the time the + // service took to respond. Both are zero when the phase failed. + Duration time.Duration + Connect time.Duration + + // Err is the error the phase failed with, nil when it succeeded. + Err error +} + +// IterationResult is the outcome of one iteration. +type IterationResult struct { + // Seq numbers the iterations from 1 in the order they were handed out. + Seq int + + // Start is when the iteration started, as an offset from the start of + // the run. + Start time.Duration + + SandboxID string + + // Phases lists the phases the iteration ran, in the order it ran them, + // followed by PhaseTotal when every phase succeeded. A successful untimed + // step leaves no entry; a phase never reached, after a failed create say, + // leaves none either. + Phases []PhaseResult + + // Leaked lists the sandboxes the iteration created but could not kill. + Leaked []string +} + +// Succeeded reports whether every phase of the iteration succeeded. +func (r IterationResult) Succeeded() bool { + for _, p := range r.Phases { + if p.Err != nil { + return false + } + } + return true +} + +// Run runs opts.Count iterations with at most opts.Concurrency of them in +// flight. An iteration creates a sandbox, runs opts.Steps on it and kills it. +// +// Cancelling ctx stops new iterations from starting. Iterations already in +// flight run to completion on a context detached from ctx, so every sandbox +// they created is still killed (unless SkipKill is set). +func Run[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) Report { + count := max(opts.Count, 0) + concurrency := min(max(opts.Concurrency, 1), max(count, 1)) + + // In-flight iterations must be able to clean up after a cancellation. + iterCtx := context.WithoutCancel(ctx) + + jobs := make(chan int) + var ( + mu sync.Mutex + results = make([]IterationResult, 0, count) + progress = Progress{Total: count} + wg sync.WaitGroup + ) + + start := time.Now() + + for range concurrency { + wg.Go(func() { + for seq := range jobs { + // The dispatcher may hand out a job in the same instant ctx is + // cancelled; drop it rather than start a new sandbox. + if ctx.Err() != nil { + continue + } + + result := runIteration(iterCtx, create, opts, seq, start) + + mu.Lock() + results = append(results, result) + progress.Done++ + if result.Succeeded() { + progress.Succeeded++ + } else { + progress.Failed++ + } + if opts.OnIteration != nil { + opts.OnIteration(progress) + } + mu.Unlock() + } + }) + } + +dispatch: + for seq := 1; seq <= count; seq++ { + select { + case <-ctx.Done(): + break dispatch + case jobs <- seq: + } + } + close(jobs) + wg.Wait() + + // A cancellation that arrives after the last iteration started cut nothing + // short, so only iterations that never ran mark the run as interrupted. + interrupted := len(results) < count + + return buildReport(results, count, opts.phases(), interrupted, time.Since(start)) +} + +// runIteration creates a sandbox, runs every step on it and kills it. The +// sandbox is killed even when a step fails. seq numbers the iteration, and +// runStart is when the run started. +func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S], seq int, runStart time.Time) IterationResult { + iterStart := time.Now() + + result := IterationResult{ + Seq: seq, + Start: iterStart.Sub(runStart), + Phases: make([]PhaseResult, 0, len(opts.Steps)+3), + } + + var sbx S + err := result.timePhase(ctx, PhaseCreate, func(ctx context.Context) error { + var err error + sbx, err = create(ctx) + return err + }) + if err != nil { + return result + } + result.SandboxID = sbx.ID() + + // untimedConnect is the connection setup time of the untimed steps. They + // get no entry of their own, but their time is part of the total, so this + // is too. + var untimedConnect time.Duration + + for _, step := range opts.Steps { + run := func(ctx context.Context) error { return step.Run(ctx, sbx) } + if step.Untimed { + untimedConnect += result.runUntimed(ctx, step.Phase, run) + } else { + result.timePhase(ctx, step.Phase, run) + } + } + + if !opts.SkipKill { + killErr := result.timePhase(ctx, PhaseKill, sbx.Kill) + if killErr != nil && !errors.Is(killErr, ErrSandboxNotFound) { + result.Leaked = append(result.Leaked, result.SandboxID) + } + } + + if result.Succeeded() { + connect := untimedConnect + for _, p := range result.Phases { + connect += p.Connect + } + result.Phases = append(result.Phases, PhaseResult{ + Phase: PhaseTotal, + Duration: time.Since(iterStart), + Connect: connect, + }) + } + + return result +} + +// timePhase runs one phase, recording its duration and connection setup time +// when it succeeds and its error when it fails. +func (r *IterationResult) timePhase(ctx context.Context, phase Phase, run func(context.Context) error) error { + traced, conn := withConnTrace(ctx) + + start := time.Now() + if err := run(traced); err != nil { + r.fail(phase, err) + return err + } + r.Phases = append(r.Phases, PhaseResult{Phase: phase, Duration: time.Since(start), Connect: conn.Total()}) + + return nil +} + +// runUntimed runs an untimed step, recording only its error. It returns the +// time the step spent obtaining HTTP connections. +func (r *IterationResult) runUntimed(ctx context.Context, phase Phase, run func(context.Context) error) time.Duration { + traced, conn := withConnTrace(ctx) + if err := run(traced); err != nil { + r.fail(phase, err) + } + return conn.Total() +} + +// fail records the error of a phase, and the sandboxes it leaked. +func (r *IterationResult) fail(phase Phase, err error) { + r.Phases = append(r.Phases, PhaseResult{Phase: phase, Err: err}) + + if leaked, ok := errors.AsType[*LeakedError](err); ok { + r.Leaked = append(r.Leaked, leaked.IDs...) + } +} diff --git a/internal/benchmark/stats.go b/internal/benchmark/stats.go new file mode 100644 index 0000000..e62794f --- /dev/null +++ b/internal/benchmark/stats.go @@ -0,0 +1,52 @@ +package benchmark + +import ( + "math" + "slices" + "time" +) + +// Stats summarizes a set of latency samples. +type Stats struct { + Count int + Avg time.Duration + Min time.Duration + P50 time.Duration + P95 time.Duration + P99 time.Duration + Max time.Duration +} + +// Summarize computes the latency statistics of samples. An empty input yields +// zero Stats. The input slice is left untouched. +func Summarize(samples []time.Duration) Stats { + if len(samples) == 0 { + return Stats{} + } + + sorted := slices.Clone(samples) + slices.Sort(sorted) + + var sum time.Duration + for _, s := range sorted { + sum += s + } + + return Stats{ + Count: len(sorted), + Avg: sum / time.Duration(len(sorted)), + Min: sorted[0], + P50: percentile(sorted, 50), + P95: percentile(sorted, 95), + P99: percentile(sorted, 99), + Max: sorted[len(sorted)-1], + } +} + +// percentile returns the p-th percentile of sorted using the nearest-rank +// method, so the result is always one of the observed samples. +func percentile(sorted []time.Duration, p float64) time.Duration { + rank := int(math.Ceil(p / 100 * float64(len(sorted)))) + rank = min(max(rank, 1), len(sorted)) + return sorted[rank-1] +} diff --git a/internal/config/config.go b/internal/config/config.go index f8afc0d..63d92aa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,8 +13,10 @@ import ( ) const ( - defaultDomain = "cn-wlcb.sandbox.ucloudai.com" - domainTemplate = "%s.sandbox.ucloudai.com" + defaultRegion = "cn-wlcb" + defaultDomain = defaultRegion + ".sandbox.ucloudai.com" + domainSuffix = ".sandbox.ucloudai.com" + domainTemplate = "%s" + domainSuffix configDir = ".ucloud-sandbox-cli" configFile = "config.json" @@ -161,15 +163,38 @@ func resolveDomain(cfg *Config) string { return defaultDomain } -// NewClient validates the config and creates a sandbox client. -func NewClient(cfg *Config) (*client.Client, error) { +// ResolveRegion returns the region the API calls go to. The domain takes +// precedence over the region there, so a domain of the ".sandbox. +// ucloudai.com" form names the region; a custom domain names none, and the +// configured region is assumed to match it. ok is false when neither tells +// the region. +func ResolveRegion(cfg *Config) (region string, ok bool) { + if cfg.Domain != "" { + if r, found := strings.CutSuffix(cfg.Domain, domainSuffix); found && r != "" && !strings.Contains(r, ".") { + return r, true + } + return cfg.Region, cfg.Region != "" + } + if cfg.Region != "" { + return cfg.Region, true + } + return defaultRegion, true +} + +// NewClient validates the config and creates a sandbox client. Each modifier +// adjusts the SDK options after they are filled in from cfg, for commands that +// need a client tuned differently from the default. +func NewClient(cfg *Config, modifiers ...func(*client.Options)) (*client.Client, error) { if cfg.APIKey == "" { return nil, errors.New("API key is required; set it in config or via UCLOUD_SANDBOX_API_KEY") } - domain := resolveDomain(cfg) - return client.New(client.Options{ + opts := client.Options{ APIKey: cfg.APIKey, - Domain: domain, + Domain: resolveDomain(cfg), InsecureHTTP: cfg.InsecureHTTP, - }) + } + for _, modify := range modifiers { + modify(&opts) + } + return client.New(opts) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 5dae13a..36845e5 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/ucloud/ucloud-sandbox-sdk-go/pkg/client" ) func setupHome(t *testing.T) string { @@ -226,3 +227,40 @@ func TestNewClient_OK(t *testing.T) { require.NoError(t, err) assert.NotNil(t, client) } + +func TestNewClient_AppliesModifiers(t *testing.T) { + var seen client.Options + _, err := NewClient(&Config{APIKey: "test-key", Region: "cn-test"}, + func(o *client.Options) { o.Domain = "example.com" }, + func(o *client.Options) { seen = *o }, + ) + require.NoError(t, err) + + assert.Equal(t, "test-key", seen.APIKey, "modifiers see the options filled in from the config") + assert.Equal(t, "example.com", seen.Domain, "modifiers run in order") +} + +func TestResolveRegion(t *testing.T) { + tests := []struct { + name string + cfg Config + region string + ok bool + }{ + {"default region", Config{}, "cn-wlcb", true}, + {"region", Config{Region: "us-ca"}, "us-ca", true}, + {"region from domain", Config{Domain: "cn-sh.sandbox.ucloudai.com"}, "cn-sh", true}, + {"domain wins, as for the API", Config{Region: "us-ca", Domain: "cn-sh.sandbox.ucloudai.com"}, "cn-sh", true}, + {"custom domain with region", Config{Region: "us-ca", Domain: "sandbox.example.com"}, "us-ca", true}, + {"custom domain alone", Config{Domain: "sandbox.example.com"}, "", false}, + {"bare suffix", Config{Domain: "sandbox.ucloudai.com"}, "", false}, + {"nested subdomain", Config{Domain: "a.b.sandbox.ucloudai.com"}, "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + region, ok := ResolveRegion(&tt.cfg) + assert.Equal(t, tt.region, region) + assert.Equal(t, tt.ok, ok) + }) + } +} diff --git a/internal/table/table.go b/internal/table/table.go index f4c008e..dc1ac63 100644 --- a/internal/table/table.go +++ b/internal/table/table.go @@ -36,6 +36,17 @@ type column struct { // (returned by the backend / service), used to compute the total page count // in the header. The trailing newline is included. func Render(items any, page, pageSize int, total int64) (string, error) { + body, err := RenderPlain(items) + if err != nil { + return "", err + } + return renderHeader(page, pageSize, total) + "\n" + body, nil +} + +// RenderPlain renders items as an ASCII table without the pagination header. +// It follows the same column rules as Render; an element type without columns +// renders as an empty string. +func RenderPlain(items any) (string, error) { rv := reflect.ValueOf(items) if !rv.IsValid() { return "", fmt.Errorf("table: items is nil") @@ -71,8 +82,6 @@ func Render(items any, page, pageSize int, total int64) (string, error) { widths := computeWidths(cols, body) var b strings.Builder - b.WriteString(renderHeader(page, pageSize, total)) - b.WriteByte('\n') if len(cols) == 0 { return b.String(), nil } diff --git a/internal/table/table_test.go b/internal/table/table_test.go index 699dd1b..6e2fe83 100644 --- a/internal/table/table_test.go +++ b/internal/table/table_test.go @@ -96,6 +96,23 @@ func TestRender_Errors(t *testing.T) { assert.Error(t, err) // element must be a struct } +func TestRenderPlain_OmitsPaginationHeader(t *testing.T) { + out, err := RenderPlain([]sample{{Title: "x"}}) + require.NoError(t, err) + assert.NotContains(t, out, "Page:") + assert.True(t, strings.HasPrefix(out, "+"), "starts with the top border, got: %q", out) + assert.Contains(t, out, "| x ") + + paged, err := Render([]sample{{Title: "x"}}, 1, 20, 1) + require.NoError(t, err) + assert.Equal(t, "Page: 1/1, Total: 1\n"+out, paged) +} + +func TestRenderPlain_Errors(t *testing.T) { + _, err := RenderPlain("not a slice") + assert.Error(t, err) +} + func TestRender_TotalPages(t *testing.T) { // page-size 0 with non-zero total -> 1 page. out, err := Render([]sample{{Title: "x"}}, 1, 0, 5) diff --git a/main.go b/main.go index f2e03ac..a10ae46 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/ucloud/ucloud-sandbox-cli/cmd/auth" + "github.com/ucloud/ucloud-sandbox-cli/cmd/benchmark" "github.com/ucloud/ucloud-sandbox-cli/cmd/sandbox" "github.com/ucloud/ucloud-sandbox-cli/cmd/secret" "github.com/ucloud/ucloud-sandbox-cli/cmd/snapshot" @@ -36,6 +37,7 @@ func newCommand() *cobra.Command { } c.AddCommand(auth.Command()) + c.AddCommand(benchmark.Command()) c.AddCommand(sandbox.Command()) c.AddCommand(secret.Command()) c.AddCommand(snapshot.Command())