From 301c9e1297744781bba32b7c7f9fd59a2976f687 Mon Sep 17 00:00:00 2001 From: joohwan Date: Wed, 25 Nov 2026 13:47:45 +0800 Subject: [PATCH 1/8] feat: add benchmark create and lifecycle commands Add a top-level `benchmark` (alias `bench`) command group that measures sandbox service latency through the SDK: - `benchmark lifecycle` times create, first exec and kill per iteration - `benchmark create` times create alone and leaves sandboxes to time out Each phase reports avg/min/P50/P95/P99/max, split into connection setup (DNS, dial, TLS via httptrace) and service time. The SDK's 429 retry is disabled so rate limiting surfaces as errors instead of latency. Sandboxes are tagged with a unique run ID and the sandbox-bench manage-by marker, and the output prints the command that cleans them up. Also let config.NewClient take option modifiers and add table.RenderPlain for tables without the pagination header. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/benchmark.go | 18 + cmd/benchmark/benchmark_test.go | 413 +++++++++++++++++++++++ cmd/benchmark/create.go | 33 ++ cmd/benchmark/lifecycle.go | 48 +++ cmd/benchmark/run.go | 221 +++++++++++++ cmd/benchmark/view.go | 245 ++++++++++++++ internal/benchmark/benchmark_test.go | 476 +++++++++++++++++++++++++++ internal/benchmark/conntrace.go | 53 +++ internal/benchmark/lifecycle.go | 241 ++++++++++++++ internal/benchmark/report.go | 161 +++++++++ internal/benchmark/stats.go | 52 +++ internal/config/config.go | 17 +- internal/config/config_test.go | 13 + internal/table/table.go | 13 +- internal/table/table_test.go | 17 + main.go | 2 + 16 files changed, 2015 insertions(+), 8 deletions(-) create mode 100644 cmd/benchmark/benchmark.go create mode 100644 cmd/benchmark/benchmark_test.go create mode 100644 cmd/benchmark/create.go create mode 100644 cmd/benchmark/lifecycle.go create mode 100644 cmd/benchmark/run.go create mode 100644 cmd/benchmark/view.go create mode 100644 internal/benchmark/benchmark_test.go create mode 100644 internal/benchmark/conntrace.go create mode 100644 internal/benchmark/lifecycle.go create mode 100644 internal/benchmark/report.go create mode 100644 internal/benchmark/stats.go diff --git a/cmd/benchmark/benchmark.go b/cmd/benchmark/benchmark.go new file mode 100644 index 0000000..68f9f60 --- /dev/null +++ b/cmd/benchmark/benchmark.go @@ -0,0 +1,18 @@ +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(&lifecycleOperation{})) + return c +} diff --git a/cmd/benchmark/benchmark_test.go b/cmd/benchmark/benchmark_test.go new file mode 100644 index 0000000..2271dea --- /dev/null +++ b/cmd/benchmark/benchmark_test.go @@ -0,0 +1,413 @@ +package benchmark + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "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.exec.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["throughput_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":[]`) +} + +func TestLifecycleViewPretty(t *testing.T) { + var b strings.Builder + require.NoError(t, newRunView("run-1", "system/base", 2, 300, sampleReport()).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, "| 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 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.RunLifecycle(context.Background(), newCreator(sdk.Sandboxes(), "run-1", op.template, op.timeout, op.exec), + benchmark.LifecycleOptions{Count: 1, Concurrency: 1, SkipExec: true}) + + 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.RunLifecycle(context.Background(), + newCreator(sdk.Sandboxes(), "run-1", "tpl", 300, execOptions{}), + benchmark.LifecycleOptions{Count: 3, Concurrency: 2, SkipExec: true, 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()) +} + +// TestSDKInstanceKillNotFound pins the SDK contract sdkInstance.Kill relies +// on: only a 404 reads as not found, any other failure stays an error of its +// own. +func TestSDKInstanceKillNotFound(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) + + inst, err := newCreator(sdk.Sandboxes(), "run-1", "tpl", 300, execOptions{})(context.Background()) + require.NoError(t, err) + + err = inst.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, "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) +} diff --git a/cmd/benchmark/create.go b/cmd/benchmark/create.go new file mode 100644 index 0000000..7e71b28 --- /dev/null +++ b/cmd/benchmark/create.go @@ -0,0 +1,33 @@ +package benchmark + +import ( + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" +) + +// 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, "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 + } + return o.run(ctx, "create", execOptions{}, benchmark.LifecycleOptions{SkipExec: true, SkipKill: true}) +} diff --git a/cmd/benchmark/lifecycle.go b/cmd/benchmark/lifecycle.go new file mode 100644 index 0000000..8018cbc --- /dev/null +++ b/cmd/benchmark/lifecycle.go @@ -0,0 +1,48 @@ +package benchmark + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/ucloud/ucloud-sandbox-cli/cmd" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" +) + +type lifecycleOperation struct { + runOptions + + exec execOptions + 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, "Seconds each sandbox lives for, bounding any sandbox a failed kill leaves behind") + c.Flags().StringVarP(&o.exec.command, "cmd", "", "echo ok", "Command run in each sandbox during the exec phase") + c.Flags().StringVarP(&o.exec.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.exec.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 + } + return o.run(ctx, "lifecycle", o.exec, benchmark.LifecycleOptions{SkipExec: o.skipExec}) +} diff --git a/cmd/benchmark/run.go b/cmd/benchmark/run.go new file mode 100644 index 0000000..f4ac4b1 --- /dev/null +++ b/cmd/benchmark/run.go @@ -0,0 +1,221 @@ +package benchmark + +import ( + "context" + "fmt" + "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 +} + +// addFlags registers the shared flags on c. timeoutUsage describes what the +// sandbox timeout means for the command. +func (o *runOptions) addFlags(c *cobra.Command, 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", 10, "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)") +} + +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 +} + +// execOptions describe the command an iteration runs in its sandbox. +type execOptions struct { + command string + user string +} + +// run executes a benchmark named name and writes its report. phases selects +// which phases are timed; exec is only used when the exec phase is. +func (o *runOptions) run(ctx cmd.OperationContext, name string, exec execOptions, phases benchmark.LifecycleOptions) error { + sdk, err := config.NewClient(ctx.Config, withoutRetries) + if err != nil { + return err + } + + 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 is closed before the deferred stop runs, so a run + // that ends normally is not reported as interrupted. + finished := make(chan struct{}) + defer close(finished) + go func() { + select { + case <-runCtx.Done(): + stop() + fmt.Fprintf(os.Stderr, "\nInterrupted: waiting for in-flight iterations to finish (Ctrl+C again to force quit, then clean up with: %s)...\n", cleanup) + case <-finished: + } + }() + + fmt.Fprintf(os.Stderr, "Running %s benchmark %s: template %s, %d iteration(s), concurrency %d\n", + name, runID, o.template, o.count, o.concurrency) + // Said up front, so a run that is killed outright still leaves a way to + // find its sandboxes. + fmt.Fprintf(os.Stderr, "Sandboxes are tagged %s=%s; clean them up with: %s\n", runIDMetadataKey, runID, cleanup) + + showProgress := term.IsTerminal(int(os.Stderr.Fd())) + + opts := phases + opts.Count = o.count + opts.Concurrency = o.concurrency + opts.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.RunLifecycle(runCtx, newCreator(sdk.Sandboxes(), runID, o.template, o.timeout, exec), opts) + if showProgress && report.Started > 0 { + fmt.Fprintln(os.Stderr) + } + + view := newRunView(runID, o.template, o.concurrency, o.timeout, report) + if phases.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 + } + + return exitError(report) +} + +// 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, exec execOptions) benchmark.CreateFunc { + return func(ctx context.Context) (benchmark.Instance, error) { + req := api.NewSandbox{ + TemplateID: template, + Timeout: &timeout, + Metadata: &api.SandboxMetadata{runIDMetadataKey: runID}, + } + + sbx, err := svc.Create(ctx, req, manageBy) + if err != nil { + return nil, err + } + + return &sdkInstance{sbx: sbx, exec: exec}, nil + } +} + +// sdkInstance adapts an SDK sandbox to benchmark.Instance. +type sdkInstance struct { + sbx *sandbox.Sandbox + exec execOptions +} + +func (i *sdkInstance) ID() string { + return i.sbx.SandboxID +} + +func (i *sdkInstance) Exec(ctx context.Context) error { + // Run reports a non-zero exit as an error, which counts as a failed exec. + _, err := i.sbx.Commands().User(i.exec.user).Run(ctx, i.exec.command, commands.Options{}) + return err +} + +// Kill relies on the SDK's contract for Sandbox.Kill: (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 (i *sdkInstance) Kill(ctx context.Context) error { + killed, err := i.sbx.Kill(ctx) + if err != nil { + return err + } + if !killed { + return benchmark.ErrSandboxNotFound + } + return nil +} diff --git a/cmd/benchmark/view.go b/cmd/benchmark/view.go new file mode 100644 index 0000000..7b4295f --- /dev/null +++ b/cmd/benchmark/view.go @@ -0,0 +1,245 @@ +package benchmark + +import ( + "fmt" + "io" + "strconv" + "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"` + Throughput float64 `json:"throughput_per_sec"` + + Phases []phaseView `json:"phases"` + Errors []errorView `json:"errors"` + Leaked []string `json:"leaked"` + + // LeftRunning counts the sandboxes the run left running on purpose, to be + // reclaimed by their timeout. + LeftRunning int `json:"left_running"` +} + +// 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), + } +} + +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), + Throughput: r.Throughput(), + Phases: make([]phaseView, 0, len(r.Phases)), + Errors: make([]errorView, 0, len(r.Errors)), + Leaked: append([]string{}, r.Leaked...), + } + + 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}) + } + + 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"` +} + +// 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.Throughput, 'f', 2, 64)) + + // Every phase is followed by its breakdown: the time spent obtaining HTTP + // connections (DNS, dial, TLS), and the rest, spent on the service. + 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 + } + 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) + + 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) + } + hint = "Clean them up 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.createFailed(); 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" + } + + 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)) + } +} + +// createFailed returns the number of iterations whose create failed. +func (v runView) createFailed() int { + for _, p := range v.Phases { + if p.Phase == string(benchmark.PhaseCreate) { + return p.Failed + } + } + return 0 +} + +// 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..c2b9c8c --- /dev/null +++ b/internal/benchmark/benchmark_test.go @@ -0,0 +1,476 @@ +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) +} + +// fakeInstance is an Instance whose phases fail as configured. +type fakeInstance struct { + id string + execErr error + killErr error + + execCalls atomic.Int32 + killCalls atomic.Int32 +} + +func (f *fakeInstance) ID() string { return f.id } + +func (f *fakeInstance) Exec(context.Context) error { + f.execCalls.Add(1) + return f.execErr +} + +func (f *fakeInstance) Kill(context.Context) error { + f.killCalls.Add(1) + return f.killErr +} + +// fakeService hands out fakeInstances and records them. +type fakeService struct { + mu sync.Mutex + instances []*fakeInstance + created atomic.Int32 + + // configure, when set, decides the behavior of the n-th (0-based) create. + configure func(n int, inst *fakeInstance) error +} + +func (s *fakeService) create(context.Context) (Instance, error) { + n := int(s.created.Add(1)) - 1 + inst := &fakeInstance{id: fmt.Sprintf("sbx-%03d", n)} + + if s.configure != nil { + if err := s.configure(n, inst); err != nil { + return nil, err + } + } + + s.mu.Lock() + s.instances = append(s.instances, inst) + s.mu.Unlock() + + return inst, nil +} + +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 TestRunLifecycleAllSucceed(t *testing.T) { + svc := &fakeService{} + + var calls []Progress + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + 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 _, inst := range svc.instances { + assert.EqualValues(t, 1, inst.execCalls.Load()) + assert.EqualValues(t, 1, inst.killCalls.Load()) + } + + require.Len(t, calls, 20) + assert.Equal(t, Progress{Done: 20, Total: 20, Succeeded: 20}, calls[19]) +} + +func TestRunLifecycleSkipExec(t *testing.T) { + svc := &fakeService{} + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + Count: 3, + Concurrency: 1, + SkipExec: true, + }) + + var phases []Phase + for _, p := range report.Phases { + phases = append(phases, p.Phase) + } + assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, phases) + + for _, inst := range svc.instances { + assert.EqualValues(t, 0, inst.execCalls.Load()) + assert.EqualValues(t, 1, inst.killCalls.Load()) + } +} + +func TestRunLifecycleFailures(t *testing.T) { + svc := &fakeService{ + configure: func(n int, inst *fakeInstance) error { + switch n % 5 { + case 1: + return errors.New("quota exceeded") + case 2: + inst.execErr = errors.New("exit status 1") + case 3: + inst.killErr = errors.New("kill timeout") + case 4: + inst.killErr = fmt.Errorf("wrapped: %w", ErrSandboxNotFound) + } + return nil + }, + } + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + 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 _, inst := range svc.instances { + assert.EqualValues(t, 1, inst.killCalls.Load(), inst.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 TestRunLifecycleErrorsSortedByCount(t *testing.T) { + svc := &fakeService{ + configure: func(n int, _ *fakeInstance) error { + if n == 0 { + return errors.New("rare") + } + return errors.New("common") + }, + } + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{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 TestRunLifecycleRespectsConcurrency(t *testing.T) { + var inFlight, peak atomic.Int32 + + create := func(context.Context) (Instance, 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 &fakeInstance{id: "sbx"}, nil + } + + report := RunLifecycle(context.Background(), create, LifecycleOptions{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 TestRunLifecycleCancelStopsNewIterationsAndCleansUp(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + svc := &fakeService{} + release := make(chan struct{}) + + create := func(c context.Context) (Instance, error) { + inst, err := svc.create(c) + if svc.created.Load() == 2 { + // The second iteration is in flight when the run is cancelled. + cancel() + <-release + } + return inst, err + } + + go func() { + <-ctx.Done() + close(release) + }() + + report := RunLifecycle(ctx, create, LifecycleOptions{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") + + for _, inst := range svc.instances { + assert.EqualValues(t, 1, inst.killCalls.Load(), inst.id) + } +} + +func TestRunLifecycleZeroCount(t *testing.T) { + svc := &fakeService{} + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{Count: 0, Concurrency: 5}) + + assert.Equal(t, 0, report.Started) + assert.EqualValues(t, 0, svc.created.Load()) +} + +func TestReportThroughput(t *testing.T) { + assert.InDelta(t, 2.5, Report{Succeeded: 5, Elapsed: 2 * time.Second}.Throughput(), 1e-9) + assert.Zero(t, Report{Succeeded: 5}.Throughput()) +} + +// 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()) +} + +// connectingInstance spends connect obtaining a connection, then work +// responding, in every phase. +type connectingInstance struct { + connect, work time.Duration +} + +func (i connectingInstance) phase(ctx context.Context) error { + simulateConnect(ctx, i.connect) + time.Sleep(i.work) + return nil +} + +func (i connectingInstance) ID() string { return "sbx" } +func (i connectingInstance) Exec(ctx context.Context) error { return i.phase(ctx) } +func (i connectingInstance) Kill(ctx context.Context) error { return i.phase(ctx) } + +func TestRunLifecycleSplitsConnectFromService(t *testing.T) { + const connect, work = 20 * time.Millisecond, 10 * time.Millisecond + inst := connectingInstance{connect: connect, work: work} + + create := func(ctx context.Context) (Instance, error) { + return inst, inst.phase(ctx) + } + + report := RunLifecycle(context.Background(), create, LifecycleOptions{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 TestRunLifecycleFailedPhaseRecordsNoConnect(t *testing.T) { + svc := &fakeService{ + configure: func(_ int, inst *fakeInstance) error { + inst.execErr = errors.New("boom") + return nil + }, + } + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{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 TestRunLifecycleCreateOnly(t *testing.T) { + svc := &fakeService{ + configure: func(n int, _ *fakeInstance) error { + if n == 0 { + return errors.New("quota exceeded") + } + return nil + }, + } + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + Count: 4, + Concurrency: 2, + SkipExec: true, + 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.instances, 3) + for _, inst := range svc.instances { + assert.EqualValues(t, 0, inst.execCalls.Load(), inst.id) + assert.EqualValues(t, 0, inst.killCalls.Load(), inst.id) + } +} + +func TestLifecycleOptionsPhases(t *testing.T) { + assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseKill, PhaseTotal}, LifecycleOptions{}.phases()) + assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, LifecycleOptions{SkipExec: true}.phases()) + assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseTotal}, LifecycleOptions{SkipKill: true}.phases()) + assert.Equal(t, []Phase{PhaseCreate}, LifecycleOptions{SkipExec: true, SkipKill: true}.phases()) +} + +func TestNormalizeMessage(t *testing.T) { + assert.Equal(t, + "command exited with code 127: bash: nope: command not found", + normalizeMessage("command exited with code 127: bash: nope: command not found\n", "sbx-1")) + assert.Equal(t, + "line one line two", + normalizeMessage(" line one\n\tline two\r\n", "")) + assert.Equal(t, + `Post "https://49983-.example.com/process.Process/Start": dial tcp: i/o timeout`, + normalizeMessage(`Post "https://49983-ibx7k2.example.com/process.Process/Start": dial tcp: i/o timeout`, "ibx7k2")) +} + +func TestRunLifecycleGroupsErrorsAcrossSandboxes(t *testing.T) { + svc := &fakeService{ + configure: func(n int, inst *fakeInstance) error { + // Every exec fails with a message naming its own sandbox and + // spanning several lines. + inst.execErr = fmt.Errorf("dial https://49983-%s.example.com: refused\nretry later\n", inst.id) + return nil + }, + } + + report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{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]) +} 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/lifecycle.go b/internal/benchmark/lifecycle.go new file mode 100644 index 0000000..932d267 --- /dev/null +++ b/internal/benchmark/lifecycle.go @@ -0,0 +1,241 @@ +// Package benchmark measures the latency of sandbox operations under load. +// +// The runner is decoupled from the SDK: it drives Instance values handed out +// by a CreateFunc, so the scheduling and statistics can be tested without a +// real sandbox service. +package benchmark + +import ( + "context" + "errors" + "sync" + "time" +) + +// Phase names one timed step of a lifecycle 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 Instance.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)") + +// Instance is a sandbox created by an iteration. +type Instance interface { + ID() string + Exec(ctx context.Context) error + Kill(ctx context.Context) error +} + +// CreateFunc creates the sandbox one iteration works on. +type CreateFunc func(ctx context.Context) (Instance, error) + +// LifecycleOptions shape a lifecycle benchmark run. +type LifecycleOptions struct { + // Count is the number of iterations to run. + Count int + + // Concurrency is the number of iterations in flight at once. + Concurrency int + + // SkipExec leaves out the exec phase, so an iteration is create then kill. + SkipExec bool + + // 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) +} + +// Progress is the running state of a benchmark, as reported to OnIteration. +type Progress struct { + Done int + Total int + Succeeded int + Failed int +} + +// PhaseError is the failure of one phase of an iteration. +type PhaseError struct { + Phase Phase + Err error +} + +// IterationResult is the outcome of one iteration. +type IterationResult struct { + SandboxID string + + // Durations holds the time taken by every phase that succeeded. + Durations map[Phase]time.Duration + + // Connects holds, for every phase in Durations, the part of its time spent + // obtaining HTTP connections (DNS, dial, TLS). The rest is the time the + // service took to respond. + Connects map[Phase]time.Duration + + // Errors lists the phases that failed, in the order they ran. + Errors []PhaseError + + // Leaked reports that the sandbox was created but could not be killed. + Leaked bool +} + +// 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 LifecycleOptions) phases() []Phase { + phases := []Phase{PhaseCreate} + if !o.SkipExec { + phases = append(phases, PhaseExec) + } + if !o.SkipKill { + phases = append(phases, PhaseKill) + } + if len(phases) > 1 { + phases = append(phases, PhaseTotal) + } + return phases +} + +// Succeeded reports whether every phase of the iteration succeeded. +func (r IterationResult) Succeeded() bool { + return len(r.Errors) == 0 +} + +// RunLifecycle runs opts.Count create → exec → kill iterations with at most +// opts.Concurrency of them in flight. SkipExec and SkipKill leave phases out. +// +// 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 RunLifecycle(ctx context.Context, create CreateFunc, opts LifecycleOptions) 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 struct{}) + 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 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) + + 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 range count { + select { + case <-ctx.Done(): + break dispatch + case jobs <- struct{}{}: + } + } + 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 runs one create → exec → kill sequence, leaving out the phases +// opts skips. The sandbox is killed even when exec fails. +func runIteration(ctx context.Context, create CreateFunc, opts LifecycleOptions) IterationResult { + result := IterationResult{ + Durations: make(map[Phase]time.Duration, 4), + Connects: make(map[Phase]time.Duration, 4), + } + + iterStart := time.Now() + + var instance Instance + err := result.timePhase(ctx, PhaseCreate, func(ctx context.Context) error { + var err error + instance, err = create(ctx) + return err + }) + if err != nil { + return result + } + result.SandboxID = instance.ID() + + if !opts.SkipExec { + result.timePhase(ctx, PhaseExec, instance.Exec) + } + + if !opts.SkipKill { + killErr := result.timePhase(ctx, PhaseKill, instance.Kill) + result.Leaked = killErr != nil && !errors.Is(killErr, ErrSandboxNotFound) + } + + if result.Succeeded() { + var connect time.Duration + for _, d := range result.Connects { + connect += d + } + result.Durations[PhaseTotal] = time.Since(iterStart) + result.Connects[PhaseTotal] = 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.Errors = append(r.Errors, PhaseError{Phase: phase, Err: err}) + return err + } + r.Durations[phase] = time.Since(start) + r.Connects[phase] = conn.Total() + + return nil +} diff --git a/internal/benchmark/report.go b/internal/benchmark/report.go new file mode 100644 index 0000000..93c1778 --- /dev/null +++ b/internal/benchmark/report.go @@ -0,0 +1,161 @@ +package benchmark + +import ( + "cmp" + "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 +} + +// 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 +} + +// Throughput returns the number of successful iterations per second. +func (r Report) Throughput() 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 phase, d := range r.Durations { + connect := r.Connects[phase] + samples[phase] = append(samples[phase], d) + connects[phase] = append(connects[phase], connect) + services[phase] = append(services[phase], d-connect) + } + + for _, e := range r.Errors { + failed[e.Phase]++ + + key := errorKey{phase: e.Phase, message: normalizeMessage(e.Err.Error(), r.SandboxID)} + if errorCounts[key] == 0 { + errorOrder = append(errorOrder, key) + } + errorCounts[key]++ + } + + if r.Leaked { + report.Leaked = append(report.Leaked, r.SandboxID) + } + } + + 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) + + return report +} + +// sandboxPlaceholder stands in for the sandbox ID in a normalized message. +const sandboxPlaceholder = "" + +// normalizeMessage prepares an error message for grouping and display. 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(msg, sandboxID string) string { + if sandboxID != "" { + msg = strings.ReplaceAll(msg, sandboxID, sandboxPlaceholder) + } + return strings.Join(strings.Fields(msg), " ") +} 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..adc0745 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -161,15 +161,20 @@ func resolveDomain(cfg *Config) string { return defaultDomain } -// NewClient validates the config and creates a sandbox client. -func NewClient(cfg *Config) (*client.Client, error) { +// 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..be3480e 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,15 @@ 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") +} 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()) From 866fdff243e84fa6379b5f4c0892821f56a364e5 Mon Sep 17 00:00:00 2001 From: joohwan Date: Wed, 25 Nov 2026 23:04:29 +0800 Subject: [PATCH 2/8] feat: add benchmark health command Add `benchmark health`, which puts every sandbox through a series of checks between create and kill and reports each as its own phase: - exec: run a command - filesystem: write a random token through envd and read it back - internet: curl each --url and require HTTP 200 (default: Apple's connectivity probe, reachable from every region) - intranet: sudo ping the region's internal US3 endpoint (internal.s3-.ufileos.com, cn-sh uses cn-sh2) - public-url: serve a token inside the sandbox and fetch it through the sandbox's public URL - pause: pause, resume and run a command again --skip and --only select checks. A failing check does not stop the ones after it. To support it, the runner now takes a list of steps run on each sandbox, so lifecycle, create and health share one implementation. Also rename the JSON field throughput_per_sec to rate_per_sec, print the run header one item per line, and add config.ResolveRegion. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/benchmark.go | 1 + cmd/benchmark/benchmark_test.go | 37 +- cmd/benchmark/create.go | 9 +- cmd/benchmark/health.go | 456 ++++++++++++++++++ cmd/benchmark/health_test.go | 232 +++++++++ cmd/benchmark/lifecycle.go | 23 +- cmd/benchmark/run.go | 138 ++++-- cmd/benchmark/view.go | 15 +- internal/benchmark/benchmark_test.go | 216 +++++---- internal/benchmark/report.go | 4 +- .../benchmark/{lifecycle.go => runner.go} | 97 ++-- internal/config/config.go | 12 +- internal/config/config_test.go | 5 + 13 files changed, 1042 insertions(+), 203 deletions(-) create mode 100644 cmd/benchmark/health.go create mode 100644 cmd/benchmark/health_test.go rename internal/benchmark/{lifecycle.go => runner.go} (72%) diff --git a/cmd/benchmark/benchmark.go b/cmd/benchmark/benchmark.go index 68f9f60..e41cdac 100644 --- a/cmd/benchmark/benchmark.go +++ b/cmd/benchmark/benchmark.go @@ -13,6 +13,7 @@ func Command() *cobra.Command { Short: "Benchmark the sandbox service", } c.AddCommand(cmd.Build(&createOperation{})) + c.AddCommand(cmd.Build(&healthOperation{})) c.AddCommand(cmd.Build(&lifecycleOperation{})) return c } diff --git a/cmd/benchmark/benchmark_test.go b/cmd/benchmark/benchmark_test.go index 2271dea..181fc43 100644 --- a/cmd/benchmark/benchmark_test.go +++ b/cmd/benchmark/benchmark_test.go @@ -33,7 +33,7 @@ func TestLifecycleDefaults(t *testing.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.exec.command) + assert.Equal(t, "echo ok", op.command) assert.EqualValues(t, 300, op.timeout) assert.Equal(t, "pretty", op.format) assert.NoError(t, op.validate()) @@ -107,7 +107,7 @@ func TestLifecycleViewJSON(t *testing.T) { assert.Equal(t, "run-1", decoded["run_id"]) assert.InDelta(t, 4000, decoded["elapsed_ms"], 1e-9) - assert.InDelta(t, 0.5, decoded["throughput_per_sec"], 1e-9) + assert.InDelta(t, 0.5, decoded["rate_per_sec"], 1e-9) phases := decoded["phases"].([]any) require.Len(t, phases, 2) @@ -220,8 +220,8 @@ func TestLifecycleTracesSDKConnections(t *testing.T) { require.NoError(t, err) op := parseLifecycle(t, "--skip-exec") - report := benchmark.RunLifecycle(context.Background(), newCreator(sdk.Sandboxes(), "run-1", op.template, op.timeout, op.exec), - benchmark.LifecycleOptions{Count: 1, Concurrency: 1, SkipExec: true}) + 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 { @@ -299,9 +299,9 @@ func TestCreateOnlyKillsNothing(t *testing.T) { sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) require.NoError(t, err) - report := benchmark.RunLifecycle(context.Background(), - newCreator(sdk.Sandboxes(), "run-1", "tpl", 300, execOptions{}), - benchmark.LifecycleOptions{Count: 3, Concurrency: 2, SkipExec: true, SkipKill: true}) + 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) @@ -310,10 +310,10 @@ func TestCreateOnlyKillsNothing(t *testing.T) { assert.Zero(t, deletes.Load()) } -// TestSDKInstanceKillNotFound pins the SDK contract sdkInstance.Kill relies +// 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 TestSDKInstanceKillNotFound(t *testing.T) { +func TestBenchSandboxKillNotFound(t *testing.T) { tests := []struct { name string status int @@ -341,10 +341,10 @@ func TestSDKInstanceKillNotFound(t *testing.T) { sdk, err := client.New(client.Options{APIKey: "test-key", APIURL: srv.URL}) require.NoError(t, err) - inst, err := newCreator(sdk.Sandboxes(), "run-1", "tpl", 300, execOptions{})(context.Background()) + sbx, err := newCreator(sdk.Sandboxes(), "run-1", "tpl", 300)(context.Background()) require.NoError(t, err) - err = inst.Kill(context.Background()) + err = sbx.Kill(context.Background()) if !tt.wantErr { assert.NoError(t, err) return @@ -411,3 +411,18 @@ func TestRunViewCleanupHint(t *testing.T) { 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, "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 index 7e71b28..9ffda8c 100644 --- a/cmd/benchmark/create.go +++ b/cmd/benchmark/create.go @@ -3,7 +3,6 @@ package benchmark import ( "github.com/spf13/cobra" "github.com/ucloud/ucloud-sandbox-cli/cmd" - "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" ) // createOperation times sandbox creation alone. The sandboxes are not killed: @@ -20,7 +19,7 @@ func (o *createOperation) Command() *cobra.Command { Args: cobra.NoArgs, } - o.addFlags(c, "Seconds each sandbox lives for before it is reclaimed; sandboxes are not killed") + o.addFlags(c, 10, "Seconds each sandbox lives for before it is reclaimed; sandboxes are not killed") return c } @@ -29,5 +28,9 @@ func (o *createOperation) Run(ctx cmd.OperationContext) error { if err := o.validate(); err != nil { return err } - return o.run(ctx, "create", execOptions{}, benchmark.LifecycleOptions{SkipExec: true, SkipKill: true}) + 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..2d224d4 --- /dev/null +++ b/cmd/benchmark/health.go @@ -0,0 +1,456 @@ +package benchmark + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "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" +) + +// intranetHostTemplate builds a region's internal US3 (ufile) endpoint, the +// host its sandboxes should reach over the intranet. +const intranetHostTemplate = "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 + intranetHost 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.intranetHost, "intranet-host", "", "", + "Intranet host the sandbox must reach by ping (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 { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + 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.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 +} + +// 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 + } + + intranetHost := resolveIntranetHost(config.ResolveRegion(ctx.Config), o.intranetHost) + + return o.run(ctx, sdk, runSpec{ + name: "health", + steps: o.steps(sdk.Transport(), intranetHost), + hideBreakdown: true, + }) +} + +// resolveIntranetHost returns the intranet host to check: the one given by +// flag, or the region's own US3 endpoint. +func resolveIntranetHost(region, override string) string { + if override != "" { + return override + } + if alias, ok := intranetRegionAliases[region]; ok { + region = alias + } + return fmt.Sprintf(intranetHostTemplate, region) +} + +// steps returns the steps of the selected checks, in the order of +// healthChecks. +func (o *healthOperation) steps(t *transport.Client, intranetHost 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": {pingStep(benchmark.Phase("intranet "+intranetHost), intranetHost)}, + "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. +func checkFilesystem(ctx context.Context, sbx *benchSandbox) error { + token := randomToken() + path := "/tmp/ucloud-sandbox-health-" + token + + 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) + } +} + +// pingStep checks that the sandbox reaches host with ICMP echo: the name has +// to resolve and at least one of the pings has to be answered. +func pingStep(phase benchmark.Phase, host string) benchmark.Step[*benchSandbox] { + return benchmark.Step[*benchSandbox]{ + Phase: phase, + Run: func(ctx context.Context, sbx *benchSandbox) error { + result, err := sbx.run(ctx, pingCommand(host), "") + if err == nil { + return nil + } + // A ping nobody answers explains itself on stdout, in the packet + // loss summary, and leaves stderr empty. + if result != nil { + if summary := pingSummary(result.Stdout); summary != "" && strings.TrimSpace(result.Stderr) == "" { + return fmt.Errorf("ping %s: %s", host, summary) + } + } + return fmt.Errorf("ping %s: %w", host, err) + }, + } +} + +// pingCount and pingWaitSec shape the intranet ping: how many echo requests +// are sent, and how many seconds each one waits for its reply. +const ( + pingCount = 3 + pingWaitSec = 2 +) + +// pingCommand returns the ping invocation checking host. ping exits 0 once +// any reply arrives and non-zero when none does. It runs through sudo, since +// the sandbox's default user may not be allowed to send ICMP; -n makes sudo +// fail at once rather than wait for a password nobody will type. +func pingCommand(host string) string { + return fmt.Sprintf("sudo -n ping -c %d -W %d %s", pingCount, pingWaitSec, shellQuote(host)) +} + +// pingSummary returns the packet loss line of ping's output, or "". +func pingSummary(stdout string) string { + for line := range strings.SplitSeq(stdout, "\n") { + if strings.Contains(line, "packet loss") { + return strings.TrimSpace(line) + } + } + return "" +} + +// 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() + dir := "/tmp/ucloud-sandbox-health-www-" + token + + 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 errors.New("not attempted: 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..59894c4 --- /dev/null +++ b/cmd/benchmark/health_test.go @@ -0,0 +1,232 @@ +package benchmark + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" +) + +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.intranetHost, "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"}, + } + 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()) + + 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 TestResolveIntranetHost(t *testing.T) { + assert.Equal(t, "internal.s3-cn-wlcb.ufileos.com", resolveIntranetHost("cn-wlcb", "")) + assert.Equal(t, "internal.s3-cn-sh2.ufileos.com", resolveIntranetHost("cn-sh", "")) + assert.Equal(t, "internal.s3-us-ca.ufileos.com", resolveIntranetHost("us-ca", "")) + assert.Equal(t, "internal.s3-us-den.ufileos.com", resolveIntranetHost("us-den", "")) + assert.Equal(t, "internal.s3-vn-sng.ufileos.com", resolveIntranetHost("vn-sng", "")) + + assert.Equal(t, "internal.s3-mars-1.ufileos.com", resolveIntranetHost("mars-1", ""), + "a new region follows the naming pattern") + assert.Equal(t, "10.0.0.1", resolveIntranetHost("cn-wlcb", "10.0.0.1"), "the flag wins") + assert.Equal(t, "10.0.0.1", resolveIntranetHost("mars-1", "10.0.0.1")) +} + +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 internal.s3-cn-wlcb.ufileos.com", + "public-url 8000", + "pause", + "resume", + }, phases(op.steps(nil, "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 TestPingCommand(t *testing.T) { + assert.Equal(t, "sudo -n ping -c 3 -W 2 'internal.s3-cn-wlcb.ufileos.com'", pingCommand("internal.s3-cn-wlcb.ufileos.com")) + assert.Equal(t, `sudo -n ping -c 3 -W 2 'x'"'"'; rm -rf /'`, pingCommand("x'; rm -rf /"), + "a quote in the host cannot break out") +} + +func TestPingSummary(t *testing.T) { + out := `PING internal-cn-wlcb.ufileos.com (10.0.0.1) 56(84) bytes of data. + +--- internal-cn-wlcb.ufileos.com ping statistics --- +3 packets transmitted, 0 received, 100% packet loss, time 2034ms +` + assert.Equal(t, "3 packets transmitted, 0 received, 100% packet loss, time 2034ms", pingSummary(out)) + assert.Empty(t, pingSummary("ping: unknown host")) + assert.Empty(t, pingSummary("")) +} + +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 TestRunViewHideBreakdown(t *testing.T) { + v := newRunView("run-1", "system/base", 1, 300, sampleReport()) + v.hideBreakdown = true + + var b strings.Builder + require.NoError(t, v.writePretty(&b)) + out := b.String() + + assert.Contains(t, out, "| create ") + assert.NotContains(t, out, "connect |") + assert.NotContains(t, out, "service |") +} + +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, "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 internal.s3-cn-wlcb.ufileos.com"}, + healthPhases(t, "--only", "internet,intranet")) + + assert.Equal(t, []benchmark.Phase{"exec", "intranet 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 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")) +} diff --git a/cmd/benchmark/lifecycle.go b/cmd/benchmark/lifecycle.go index 8018cbc..ea6be18 100644 --- a/cmd/benchmark/lifecycle.go +++ b/cmd/benchmark/lifecycle.go @@ -5,13 +5,13 @@ import ( "github.com/spf13/cobra" "github.com/ucloud/ucloud-sandbox-cli/cmd" - "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" ) type lifecycleOperation struct { runOptions - exec execOptions + command string + user string skipExec bool } @@ -22,9 +22,9 @@ func (o *lifecycleOperation) Command() *cobra.Command { Args: cobra.NoArgs, } - o.addFlags(c, "Seconds each sandbox lives for, bounding any sandbox a failed kill leaves behind") - c.Flags().StringVarP(&o.exec.command, "cmd", "", "echo ok", "Command run in each sandbox during the exec phase") - c.Flags().StringVarP(&o.exec.user, "user", "u", "", "User to run the exec command as") + 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 @@ -34,7 +34,7 @@ func (o *lifecycleOperation) validate() error { if err := o.runOptions.validate(); err != nil { return err } - if !o.skipExec && o.exec.command == "" { + if !o.skipExec && o.command == "" { return fmt.Errorf("--cmd cannot be empty; use --skip-exec to leave out the exec phase") } return nil @@ -44,5 +44,14 @@ func (o *lifecycleOperation) Run(ctx cmd.OperationContext) error { if err := o.validate(); err != nil { return err } - return o.run(ctx, "lifecycle", o.exec, benchmark.LifecycleOptions{SkipExec: o.skipExec}) + 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 index f4ac4b1..0890008 100644 --- a/cmd/benchmark/run.go +++ b/cmd/benchmark/run.go @@ -3,6 +3,7 @@ package benchmark import ( "context" "fmt" + "io" "math/rand/v2" "os" "os/signal" @@ -38,11 +39,12 @@ type runOptions struct { format string } -// addFlags registers the shared flags on c. timeoutUsage describes what the -// sandbox timeout means for the command. -func (o *runOptions) addFlags(c *cobra.Command, timeoutUsage string) { +// 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", 10, "Total number of iterations") + 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)") @@ -66,20 +68,30 @@ func (o *runOptions) validate() error { return nil } -// execOptions describe the command an iteration runs in its sandbox. -type execOptions struct { - command string - user string +// 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 + + // hideBreakdown leaves out the connect/service rows under every phase, + // for runs about whether things work rather than how fast. + hideBreakdown bool } -// run executes a benchmark named name and writes its report. phases selects -// which phases are timed; exec is only used when the exec phase is. -func (o *runOptions) run(ctx cmd.OperationContext, name string, exec execOptions, phases benchmark.LifecycleOptions) error { - sdk, err := config.NewClient(ctx.Config, withoutRetries) - if err != nil { - return err - } +// 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) @@ -101,30 +113,30 @@ func (o *runOptions) run(ctx cmd.OperationContext, name string, exec execOptions } }() - fmt.Fprintf(os.Stderr, "Running %s benchmark %s: template %s, %d iteration(s), concurrency %d\n", - name, runID, o.template, o.count, o.concurrency) - // Said up front, so a run that is killed outright still leaves a way to - // find its sandboxes. - fmt.Fprintf(os.Stderr, "Sandboxes are tagged %s=%s; clean them up with: %s\n", runIDMetadataKey, runID, cleanup) + o.writeHeader(os.Stderr, spec.name, runID) showProgress := term.IsTerminal(int(os.Stderr.Fd())) - opts := phases - opts.Count = o.count - opts.Concurrency = o.concurrency - opts.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) - } + 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.RunLifecycle(runCtx, newCreator(sdk.Sandboxes(), runID, o.template, o.timeout, exec), opts) + 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 phases.SkipKill && len(report.Phases) > 0 { + view.hideBreakdown = spec.hideBreakdown + if spec.skipKill && len(report.Phases) > 0 { view.LeftRunning = report.Phases[0].Stats.Count } @@ -139,6 +151,17 @@ func (o *runOptions) run(ctx cmd.OperationContext, name string, exec execOptions return exitError(report) } +// 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, name, runID string) { + fmt.Fprintf(w, "Running %s benchmark %s\n", 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) + fmt.Fprintf(w, " Cleanup: %s\n\n", cleanupCommand(runID)) +} + // 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 { @@ -173,44 +196,52 @@ func withoutRetries(opts *client.Options) { } // newCreator returns the CreateFunc that starts the sandboxes of a run. -func newCreator(svc *sandbox.Service, runID, template string, timeout int32, exec execOptions) benchmark.CreateFunc { - return func(ctx context.Context) (benchmark.Instance, error) { +func newCreator(svc *sandbox.Service, runID, template string, timeout int32) benchmark.CreateFunc[*benchSandbox] { + return func(ctx context.Context) (*benchSandbox, error) { req := api.NewSandbox{ TemplateID: template, Timeout: &timeout, Metadata: &api.SandboxMetadata{runIDMetadataKey: runID}, } - sbx, err := svc.Create(ctx, req, manageBy) + created, err := svc.Create(ctx, req, manageBy) if err != nil { return nil, err } - return &sdkInstance{sbx: sbx, exec: exec}, nil + return &benchSandbox{Sandbox: created, svc: svc, timeout: timeout}, nil } } -// sdkInstance adapts an SDK sandbox to benchmark.Instance. -type sdkInstance struct { - sbx *sandbox.Sandbox - exec execOptions +// 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 and timeout let the resume step connect to the sandbox again. + svc *sandbox.Service + 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 } -func (i *sdkInstance) ID() string { - return i.sbx.SandboxID +func (sbx *benchSandbox) ID() string { + return sbx.SandboxID } -func (i *sdkInstance) Exec(ctx context.Context) error { - // Run reports a non-zero exit as an error, which counts as a failed exec. - _, err := i.sbx.Commands().User(i.exec.user).Run(ctx, i.exec.command, commands.Options{}) - return err +// 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 relies on the SDK's contract for Sandbox.Kill: (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 (i *sdkInstance) Kill(ctx context.Context) error { - killed, err := i.sbx.Kill(ctx) +// 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 } @@ -219,3 +250,14 @@ func (i *sdkInstance) Kill(ctx context.Context) error { } 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/view.go b/cmd/benchmark/view.go index 7b4295f..cc456da 100644 --- a/cmd/benchmark/view.go +++ b/cmd/benchmark/view.go @@ -24,8 +24,8 @@ type runView struct { Failed int `json:"failed"` Interrupted bool `json:"interrupted"` - ElapsedMs float64 `json:"elapsed_ms"` - Throughput float64 `json:"throughput_per_sec"` + ElapsedMs float64 `json:"elapsed_ms"` + Rate float64 `json:"rate_per_sec"` Phases []phaseView `json:"phases"` Errors []errorView `json:"errors"` @@ -34,6 +34,9 @@ type runView struct { // LeftRunning counts the sandboxes the run left running on purpose, to be // reclaimed by their timeout. LeftRunning int `json:"left_running"` + + // hideBreakdown leaves the connect/service rows out of the pretty table. + hideBreakdown bool } // phaseView is the statistics of one phase. Its latencies cover the whole @@ -86,7 +89,7 @@ func newRunView(runID, template string, concurrency int, timeoutSec int32, r ben Failed: r.Failed, Interrupted: r.Interrupted, ElapsedMs: ms(r.Elapsed), - Throughput: r.Throughput(), + Rate: r.Rate(), Phases: make([]phaseView, 0, len(r.Phases)), Errors: make([]errorView, 0, len(r.Errors)), Leaked: append([]string{}, r.Leaked...), @@ -153,7 +156,7 @@ func (v runView) writePretty(w io.Writer) error { 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.Throughput, 'f', 2, 64)) + formatMs(v.ElapsedMs), strconv.FormatFloat(v.Rate, 'f', 2, 64)) // Every phase is followed by its breakdown: the time spent obtaining HTTP // connections (DNS, dial, TLS), and the rest, spent on the service. @@ -164,6 +167,10 @@ func (v runView) writePretty(w io.Writer) error { rows = append(rows, row) continue } + if v.hideBreakdown { + rows = append(rows, row.withLatency(p.latencyView)) + continue + } rows = append(rows, row.withLatency(p.latencyView), phaseRow{Phase: " connect"}.withLatency(p.Connect), diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go index c2b9c8c..f0ec968 100644 --- a/internal/benchmark/benchmark_test.go +++ b/internal/benchmark/benchmark_test.go @@ -55,8 +55,8 @@ func TestSummarizeSmallSetPercentiles(t *testing.T) { assert.Equal(t, time.Duration(3), s.P99) } -// fakeInstance is an Instance whose phases fail as configured. -type fakeInstance struct { +// fakeSandbox is a Sandbox whose phases fail as configured. +type fakeSandbox struct { id string execErr error killErr error @@ -65,43 +65,57 @@ type fakeInstance struct { killCalls atomic.Int32 } -func (f *fakeInstance) ID() string { return f.id } +func (f *fakeSandbox) ID() string { return f.id } -func (f *fakeInstance) Exec(context.Context) error { +func (f *fakeSandbox) Exec(context.Context) error { f.execCalls.Add(1) return f.execErr } -func (f *fakeInstance) Kill(context.Context) error { +func (f *fakeSandbox) Kill(context.Context) error { f.killCalls.Add(1) return f.killErr } -// fakeService hands out fakeInstances and records them. +// fakeService hands out fakeSandboxs and records them. type fakeService struct { mu sync.Mutex - instances []*fakeInstance + sandboxes []*fakeSandbox created atomic.Int32 // configure, when set, decides the behavior of the n-th (0-based) create. - configure func(n int, inst *fakeInstance) error + configure func(n int, sbx *fakeSandbox) error } -func (s *fakeService) create(context.Context) (Instance, error) { +func (s *fakeService) create(context.Context) (*fakeSandbox, error) { n := int(s.created.Add(1)) - 1 - inst := &fakeInstance{id: fmt.Sprintf("sbx-%03d", n)} + sbx := &fakeSandbox{id: fmt.Sprintf("sbx-%03d", n)} if s.configure != nil { - if err := s.configure(n, inst); err != nil { + if err := s.configure(n, sbx); err != nil { return nil, err } } s.mu.Lock() - s.instances = append(s.instances, inst) + s.sandboxes = append(s.sandboxes, sbx) s.mu.Unlock() - return inst, nil + 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 { @@ -115,11 +129,12 @@ func phaseReport(t *testing.T, r Report, phase Phase) PhaseReport { return PhaseReport{} } -func TestRunLifecycleAllSucceed(t *testing.T) { +func TestRunAllSucceed(t *testing.T) { svc := &fakeService{} var calls []Progress - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Steps: execSteps[*fakeSandbox](), Count: 20, Concurrency: 4, OnIteration: func(p Progress) { calls = append(calls, p) }, @@ -141,22 +156,21 @@ func TestRunLifecycleAllSucceed(t *testing.T) { } assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseKill, PhaseTotal}, phases) - for _, inst := range svc.instances { - assert.EqualValues(t, 1, inst.execCalls.Load()) - assert.EqualValues(t, 1, inst.killCalls.Load()) + 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 TestRunLifecycleSkipExec(t *testing.T) { +func TestRunSkipExec(t *testing.T) { svc := &fakeService{} - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ Count: 3, Concurrency: 1, - SkipExec: true, }) var phases []Phase @@ -165,30 +179,31 @@ func TestRunLifecycleSkipExec(t *testing.T) { } assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, phases) - for _, inst := range svc.instances { - assert.EqualValues(t, 0, inst.execCalls.Load()) - assert.EqualValues(t, 1, inst.killCalls.Load()) + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 0, sbx.execCalls.Load()) + assert.EqualValues(t, 1, sbx.killCalls.Load()) } } -func TestRunLifecycleFailures(t *testing.T) { +func TestRunFailures(t *testing.T) { svc := &fakeService{ - configure: func(n int, inst *fakeInstance) error { + configure: func(n int, sbx *fakeSandbox) error { switch n % 5 { case 1: return errors.New("quota exceeded") case 2: - inst.execErr = errors.New("exit status 1") + sbx.execErr = errors.New("exit status 1") case 3: - inst.killErr = errors.New("kill timeout") + sbx.killErr = errors.New("kill timeout") case 4: - inst.killErr = fmt.Errorf("wrapped: %w", ErrSandboxNotFound) + sbx.killErr = fmt.Errorf("wrapped: %w", ErrSandboxNotFound) } return nil }, } - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ + Steps: execSteps[*fakeSandbox](), Count: 10, Concurrency: 1, }) @@ -214,8 +229,8 @@ func TestRunLifecycleFailures(t *testing.T) { assert.Equal(t, 8, total.Failed) // A failed exec still kills the sandbox. - for _, inst := range svc.instances { - assert.EqualValues(t, 1, inst.killCalls.Load(), inst.id) + 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 @@ -230,9 +245,9 @@ func TestRunLifecycleFailures(t *testing.T) { }, report.Errors) } -func TestRunLifecycleErrorsSortedByCount(t *testing.T) { +func TestRunErrorsSortedByCount(t *testing.T) { svc := &fakeService{ - configure: func(n int, _ *fakeInstance) error { + configure: func(n int, _ *fakeSandbox) error { if n == 0 { return errors.New("rare") } @@ -240,17 +255,17 @@ func TestRunLifecycleErrorsSortedByCount(t *testing.T) { }, } - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{Count: 4, Concurrency: 1}) + 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 TestRunLifecycleRespectsConcurrency(t *testing.T) { +func TestRunRespectsConcurrency(t *testing.T) { var inFlight, peak atomic.Int32 - create := func(context.Context) (Instance, error) { + create := func(context.Context) (*fakeSandbox, error) { n := inFlight.Add(1) for { p := peak.Load() @@ -260,30 +275,30 @@ func TestRunLifecycleRespectsConcurrency(t *testing.T) { } time.Sleep(5 * time.Millisecond) inFlight.Add(-1) - return &fakeInstance{id: "sbx"}, nil + return &fakeSandbox{id: "sbx"}, nil } - report := RunLifecycle(context.Background(), create, LifecycleOptions{Count: 30, Concurrency: 3}) + 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 TestRunLifecycleCancelStopsNewIterationsAndCleansUp(t *testing.T) { +func TestRunCancelStopsNewIterationsAndCleansUp(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) svc := &fakeService{} release := make(chan struct{}) - create := func(c context.Context) (Instance, error) { - inst, err := svc.create(c) + 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 inst, err + return sbx, err } go func() { @@ -291,30 +306,30 @@ func TestRunLifecycleCancelStopsNewIterationsAndCleansUp(t *testing.T) { close(release) }() - report := RunLifecycle(ctx, create, LifecycleOptions{Count: 100, Concurrency: 1}) + 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") - for _, inst := range svc.instances { - assert.EqualValues(t, 1, inst.killCalls.Load(), inst.id) + for _, sbx := range svc.sandboxes { + assert.EqualValues(t, 1, sbx.killCalls.Load(), sbx.id) } } -func TestRunLifecycleZeroCount(t *testing.T) { +func TestRunZeroCount(t *testing.T) { svc := &fakeService{} - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{Count: 0, Concurrency: 5}) + 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 TestReportThroughput(t *testing.T) { - assert.InDelta(t, 2.5, Report{Succeeded: 5, Elapsed: 2 * time.Second}.Throughput(), 1e-9) - assert.Zero(t, Report{Succeeded: 5}.Throughput()) +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 @@ -346,31 +361,33 @@ func TestConnTraceIgnoresUnpairedGotConn(t *testing.T) { assert.Zero(t, trace.Total()) } -// connectingInstance spends connect obtaining a connection, then work +// connectingSandbox spends connect obtaining a connection, then work // responding, in every phase. -type connectingInstance struct { +type connectingSandbox struct { connect, work time.Duration } -func (i connectingInstance) phase(ctx context.Context) error { +func (i connectingSandbox) phase(ctx context.Context) error { simulateConnect(ctx, i.connect) time.Sleep(i.work) return nil } -func (i connectingInstance) ID() string { return "sbx" } -func (i connectingInstance) Exec(ctx context.Context) error { return i.phase(ctx) } -func (i connectingInstance) Kill(ctx context.Context) error { return i.phase(ctx) } +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 TestRunLifecycleSplitsConnectFromService(t *testing.T) { +func TestRunSplitsConnectFromService(t *testing.T) { const connect, work = 20 * time.Millisecond, 10 * time.Millisecond - inst := connectingInstance{connect: connect, work: work} + sbx := connectingSandbox{connect: connect, work: work} - create := func(ctx context.Context) (Instance, error) { - return inst, inst.phase(ctx) + create := func(ctx context.Context) (connectingSandbox, error) { + return sbx, sbx.phase(ctx) } - report := RunLifecycle(context.Background(), create, LifecycleOptions{Count: 2, Concurrency: 1}) + 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} { @@ -386,15 +403,15 @@ func TestRunLifecycleSplitsConnectFromService(t *testing.T) { assert.GreaterOrEqual(t, total.Service.Min, 3*work) } -func TestRunLifecycleFailedPhaseRecordsNoConnect(t *testing.T) { +func TestRunFailedPhaseRecordsNoConnect(t *testing.T) { svc := &fakeService{ - configure: func(_ int, inst *fakeInstance) error { - inst.execErr = errors.New("boom") + configure: func(_ int, sbx *fakeSandbox) error { + sbx.execErr = errors.New("boom") return nil }, } - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{Count: 1, Concurrency: 1}) + 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) @@ -402,9 +419,9 @@ func TestRunLifecycleFailedPhaseRecordsNoConnect(t *testing.T) { assert.Equal(t, 1, phaseReport(t, report, PhaseCreate).Connect.Count) } -func TestRunLifecycleCreateOnly(t *testing.T) { +func TestRunCreateOnly(t *testing.T) { svc := &fakeService{ - configure: func(n int, _ *fakeInstance) error { + configure: func(n int, _ *fakeSandbox) error { if n == 0 { return errors.New("quota exceeded") } @@ -412,10 +429,9 @@ func TestRunLifecycleCreateOnly(t *testing.T) { }, } - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{ + report := Run(context.Background(), svc.create, Options[*fakeSandbox]{ Count: 4, Concurrency: 2, - SkipExec: true, SkipKill: true, }) @@ -429,18 +445,24 @@ func TestRunLifecycleCreateOnly(t *testing.T) { assert.Equal(t, 1, report.Failed) assert.Empty(t, report.Leaked, "sandboxes left running on purpose are not leaks") - require.Len(t, svc.instances, 3) - for _, inst := range svc.instances { - assert.EqualValues(t, 0, inst.execCalls.Load(), inst.id) - assert.EqualValues(t, 0, inst.killCalls.Load(), inst.id) + 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 TestLifecycleOptionsPhases(t *testing.T) { - assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseKill, PhaseTotal}, LifecycleOptions{}.phases()) - assert.Equal(t, []Phase{PhaseCreate, PhaseKill, PhaseTotal}, LifecycleOptions{SkipExec: true}.phases()) - assert.Equal(t, []Phase{PhaseCreate, PhaseExec, PhaseTotal}, LifecycleOptions{SkipKill: true}.phases()) - assert.Equal(t, []Phase{PhaseCreate}, LifecycleOptions{SkipExec: true, SkipKill: true}.phases()) +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) { @@ -455,17 +477,17 @@ func TestNormalizeMessage(t *testing.T) { normalizeMessage(`Post "https://49983-ibx7k2.example.com/process.Process/Start": dial tcp: i/o timeout`, "ibx7k2")) } -func TestRunLifecycleGroupsErrorsAcrossSandboxes(t *testing.T) { +func TestRunGroupsErrorsAcrossSandboxes(t *testing.T) { svc := &fakeService{ - configure: func(n int, inst *fakeInstance) error { + configure: func(n int, sbx *fakeSandbox) error { // Every exec fails with a message naming its own sandbox and // spanning several lines. - inst.execErr = fmt.Errorf("dial https://49983-%s.example.com: refused\nretry later\n", inst.id) + sbx.execErr = fmt.Errorf("dial https://49983-%s.example.com: refused\nretry later\n", sbx.id) return nil }, } - report := RunLifecycle(context.Background(), svc.create, LifecycleOptions{Count: 5, Concurrency: 2}) + 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{ @@ -474,3 +496,31 @@ func TestRunLifecycleGroupsErrorsAcrossSandboxes(t *testing.T) { 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()) +} diff --git a/internal/benchmark/report.go b/internal/benchmark/report.go index 93c1778..46c8d2e 100644 --- a/internal/benchmark/report.go +++ b/internal/benchmark/report.go @@ -53,8 +53,8 @@ type ErrorCount struct { Count int } -// Throughput returns the number of successful iterations per second. -func (r Report) Throughput() float64 { +// Rate returns the number of successful iterations per second. +func (r Report) Rate() float64 { if r.Elapsed <= 0 { return 0 } diff --git a/internal/benchmark/lifecycle.go b/internal/benchmark/runner.go similarity index 72% rename from internal/benchmark/lifecycle.go rename to internal/benchmark/runner.go index 932d267..3c81b33 100644 --- a/internal/benchmark/lifecycle.go +++ b/internal/benchmark/runner.go @@ -1,8 +1,9 @@ -// Package benchmark measures the latency of sandbox operations under load. +// Package benchmark measures the latency and health of sandbox operations +// under load. // -// The runner is decoupled from the SDK: it drives Instance values handed out -// by a CreateFunc, so the scheduling and statistics can be tested without a -// real sandbox service. +// 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 ( @@ -12,7 +13,7 @@ import ( "time" ) -// Phase names one timed step of a lifecycle iteration. +// Phase names one timed step of an iteration. type Phase string const ( @@ -25,31 +26,37 @@ const ( PhaseTotal Phase = "total" ) -// ErrSandboxNotFound is returned by Instance.Kill when the service answers +// 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)") -// Instance is a sandbox created by an iteration. -type Instance interface { +// Sandbox is the sandbox an iteration creates and works on. +type Sandbox interface { ID() string - Exec(ctx context.Context) error Kill(ctx context.Context) error } // CreateFunc creates the sandbox one iteration works on. -type CreateFunc func(ctx context.Context) (Instance, error) +type CreateFunc[S Sandbox] func(ctx context.Context) (S, error) -// LifecycleOptions shape a lifecycle benchmark run. -type LifecycleOptions struct { +// Step is one timed operation run on the sandbox between create and kill. +type Step[S Sandbox] struct { + Phase Phase + Run func(ctx context.Context, sbx S) error +} + +// 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 - // SkipExec leaves out the exec phase, so an iteration is create then kill. - SkipExec bool + // 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. @@ -60,6 +67,22 @@ type LifecycleOptions struct { 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 { + 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 @@ -93,34 +116,18 @@ type IterationResult struct { Leaked bool } -// 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 LifecycleOptions) phases() []Phase { - phases := []Phase{PhaseCreate} - if !o.SkipExec { - phases = append(phases, PhaseExec) - } - if !o.SkipKill { - phases = append(phases, PhaseKill) - } - if len(phases) > 1 { - phases = append(phases, PhaseTotal) - } - return phases -} - // Succeeded reports whether every phase of the iteration succeeded. func (r IterationResult) Succeeded() bool { return len(r.Errors) == 0 } -// RunLifecycle runs opts.Count create → exec → kill iterations with at most -// opts.Concurrency of them in flight. SkipExec and SkipKill leave phases out. +// 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 RunLifecycle(ctx context.Context, create CreateFunc, opts LifecycleOptions) Report { +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)) @@ -182,33 +189,35 @@ dispatch: return buildReport(results, count, opts.phases(), interrupted, time.Since(start)) } -// runIteration runs one create → exec → kill sequence, leaving out the phases -// opts skips. The sandbox is killed even when exec fails. -func runIteration(ctx context.Context, create CreateFunc, opts LifecycleOptions) IterationResult { +// runIteration creates a sandbox, runs every step on it and kills it. The +// sandbox is killed even when a step fails. +func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) IterationResult { result := IterationResult{ - Durations: make(map[Phase]time.Duration, 4), - Connects: make(map[Phase]time.Duration, 4), + Durations: make(map[Phase]time.Duration, len(opts.Steps)+3), + Connects: make(map[Phase]time.Duration, len(opts.Steps)+3), } iterStart := time.Now() - var instance Instance + var sbx S err := result.timePhase(ctx, PhaseCreate, func(ctx context.Context) error { var err error - instance, err = create(ctx) + sbx, err = create(ctx) return err }) if err != nil { return result } - result.SandboxID = instance.ID() + result.SandboxID = sbx.ID() - if !opts.SkipExec { - result.timePhase(ctx, PhaseExec, instance.Exec) + for _, step := range opts.Steps { + result.timePhase(ctx, step.Phase, func(ctx context.Context) error { + return step.Run(ctx, sbx) + }) } if !opts.SkipKill { - killErr := result.timePhase(ctx, PhaseKill, instance.Kill) + killErr := result.timePhase(ctx, PhaseKill, sbx.Kill) result.Leaked = killErr != nil && !errors.Is(killErr, ErrSandboxNotFound) } diff --git a/internal/config/config.go b/internal/config/config.go index adc0745..a8de9b7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,7 +13,8 @@ import ( ) const ( - defaultDomain = "cn-wlcb.sandbox.ucloudai.com" + defaultRegion = "cn-wlcb" + defaultDomain = defaultRegion + ".sandbox.ucloudai.com" domainTemplate = "%s.sandbox.ucloudai.com" configDir = ".ucloud-sandbox-cli" configFile = "config.json" @@ -161,6 +162,15 @@ func resolveDomain(cfg *Config) string { return defaultDomain } +// ResolveRegion returns the configured region, or the default one when none +// is set. +func ResolveRegion(cfg *Config) string { + if cfg.Region != "" { + return cfg.Region + } + return defaultRegion +} + // 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. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index be3480e..80fd8c7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -239,3 +239,8 @@ func TestNewClient_AppliesModifiers(t *testing.T) { 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) { + assert.Equal(t, "cn-wlcb", ResolveRegion(&Config{}), "default region") + assert.Equal(t, "us-ca", ResolveRegion(&Config{Region: "us-ca"})) +} From a54a2c6c14dd04eef46f77bec6349892cb69b42e Mon Sep 17 00:00:00 2001 From: joohwan Date: Wed, 25 Nov 2026 23:04:29 +0800 Subject: [PATCH 3/8] docs: update command conventions in CLAUDE.md Describe the Command() group and Operation pattern the commands actually use, in place of the outdated NewCmd() rule. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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使用的公用包 From e176b82a3398cee60ae4e1d83f5f6e15773f716a Mon Sep 17 00:00:00 2001 From: joohwan Date: Wed, 25 Nov 2026 23:36:15 +0800 Subject: [PATCH 4/8] feat: add benchmark snapshot command and --breakdown flag Add `benchmark snapshot`, which times each step of snapshotting a sandbox and booting copies of it, checking the copies keep its files: create, write, snapshot, restore, restore-verify, fork, fork-verify, snapshot-delete, kill Snapshots are named bench-- and deleted by that name: DELETE /templates/{id} answers 404 for the "/:" ID the snapshot is created with. A 404 on delete counts as a leak, since a snapshot never expires. The copies are killed, untimed, before the snapshot is deleted. Snapshots that cannot be deleted are listed with the command that deletes them, and copies that cannot be killed are listed with a kill-by-ID command, since forks may lack the run tag. The runner gains untimed steps and LeakedError, so any step can report sandboxes it failed to kill and fail the iteration. Tables now show each phase's service time, excluding connection setup, by default; --breakdown shows the full latency with its connect and service rows, as before. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/benchmark.go | 1 + cmd/benchmark/benchmark_test.go | 29 ++- cmd/benchmark/health.go | 5 +- cmd/benchmark/health_test.go | 14 -- cmd/benchmark/run.go | 57 +++-- cmd/benchmark/snapshot.go | 298 +++++++++++++++++++++++++++ cmd/benchmark/snapshot_test.go | 293 ++++++++++++++++++++++++++ cmd/benchmark/view.go | 60 +++++- internal/benchmark/benchmark_test.go | 67 ++++++ internal/benchmark/report.go | 4 +- internal/benchmark/runner.go | 60 +++++- 11 files changed, 829 insertions(+), 59 deletions(-) create mode 100644 cmd/benchmark/snapshot.go create mode 100644 cmd/benchmark/snapshot_test.go diff --git a/cmd/benchmark/benchmark.go b/cmd/benchmark/benchmark.go index e41cdac..2131ff3 100644 --- a/cmd/benchmark/benchmark.go +++ b/cmd/benchmark/benchmark.go @@ -15,5 +15,6 @@ func Command() *cobra.Command { 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 index 181fc43..17ba700 100644 --- a/cmd/benchmark/benchmark_test.go +++ b/cmd/benchmark/benchmark_test.go @@ -132,8 +132,11 @@ func TestLifecycleViewJSONEmptyListsAreArrays(t *testing.T) { } func TestLifecycleViewPretty(t *testing.T) { + v := newRunView("run-1", "system/base", 2, 300, sampleReport()) + v.breakdown = true + var b strings.Builder - require.NoError(t, newRunView("run-1", "system/base", 2, 300, sampleReport()).writePretty(&b)) + require.NoError(t, v.writePretty(&b)) out := b.String() assert.Contains(t, out, "Benchmark run-1 completed: template system/base, concurrency 2") @@ -152,6 +155,27 @@ func TestLifecycleViewPretty(t *testing.T) { 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.NotContains(t, out, "connect") + assert.NotContains(t, out, "service") +} + +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 @@ -406,6 +430,7 @@ func TestRunViewCleanupHint(t *testing.T) { 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)) @@ -416,7 +441,7 @@ func TestWriteHeader(t *testing.T) { op := &runOptions{template: "system/base", count: 10, concurrency: 2} var b strings.Builder - op.writeHeader(&b, "health", "20261125-225910-b2bbf0") + op.writeHeader(&b, runSpec{name: "health"}, "20261125-225910-b2bbf0") assert.Equal(t, `Running health benchmark 20261125-225910-b2bbf0 Template: system/base diff --git a/cmd/benchmark/health.go b/cmd/benchmark/health.go index 2d224d4..d753a31 100644 --- a/cmd/benchmark/health.go +++ b/cmd/benchmark/health.go @@ -152,9 +152,8 @@ func (o *healthOperation) Run(ctx cmd.OperationContext) error { intranetHost := resolveIntranetHost(config.ResolveRegion(ctx.Config), o.intranetHost) return o.run(ctx, sdk, runSpec{ - name: "health", - steps: o.steps(sdk.Transport(), intranetHost), - hideBreakdown: true, + name: "health", + steps: o.steps(sdk.Transport(), intranetHost), }) } diff --git a/cmd/benchmark/health_test.go b/cmd/benchmark/health_test.go index 59894c4..22dfbf5 100644 --- a/cmd/benchmark/health_test.go +++ b/cmd/benchmark/health_test.go @@ -4,7 +4,6 @@ import ( "context" "net/http" "net/http/httptest" - "strings" "testing" "github.com/stretchr/testify/assert" @@ -166,19 +165,6 @@ func TestFetch(t *testing.T) { assert.Contains(t, err.Error(), "HTTP 502") } -func TestRunViewHideBreakdown(t *testing.T) { - v := newRunView("run-1", "system/base", 1, 300, sampleReport()) - v.hideBreakdown = true - - var b strings.Builder - require.NoError(t, v.writePretty(&b)) - out := b.String() - - assert.Contains(t, out, "| create ") - assert.NotContains(t, out, "connect |") - assert.NotContains(t, out, "service |") -} - func healthPhases(t *testing.T, args ...string) []benchmark.Phase { t.Helper() op := parseHealth(t, args...) diff --git a/cmd/benchmark/run.go b/cmd/benchmark/run.go index 0890008..9c23aeb 100644 --- a/cmd/benchmark/run.go +++ b/cmd/benchmark/run.go @@ -37,6 +37,7 @@ type runOptions struct { concurrency int timeout int32 format string + breakdown bool } // addFlags registers the shared flags on c. defaultCount is the number of @@ -48,6 +49,8 @@ func (o *runOptions) addFlags(c *cobra.Command, defaultCount int, timeoutUsage s 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().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 { @@ -79,9 +82,10 @@ type runSpec struct { // skipKill leaves the sandboxes running until their timeout. skipKill bool - // hideBreakdown leaves out the connect/service rows under every phase, - // for runs about whether things work rather than how fast. - hideBreakdown 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, @@ -113,7 +117,7 @@ func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runS } }() - o.writeHeader(os.Stderr, spec.name, runID) + o.writeHeader(os.Stderr, spec, runID) showProgress := term.IsTerminal(int(os.Stderr.Fd())) @@ -135,7 +139,10 @@ func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runS } view := newRunView(runID, o.template, o.concurrency, o.timeout, report) - view.hideBreakdown = spec.hideBreakdown + 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 } @@ -154,12 +161,19 @@ func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runS // 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, name, runID string) { - fmt.Fprintf(w, "Running %s benchmark %s\n", name, runID) +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) - fmt.Fprintf(w, " Cleanup: %s\n\n", cleanupCommand(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 @@ -198,18 +212,22 @@ func withoutRetries(opts *client.Options) { // 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) { - req := api.NewSandbox{ - TemplateID: template, - Timeout: &timeout, - Metadata: &api.SandboxMetadata{runIDMetadataKey: runID}, - } - - created, err := svc.Create(ctx, req, manageBy) + created, err := svc.Create(ctx, sandboxRequest(template, runID, timeout), manageBy) if err != nil { return nil, err } - return &benchSandbox{Sandbox: created, svc: svc, timeout: timeout}, nil + 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}, } } @@ -218,13 +236,18 @@ func newCreator(svc *sandbox.Service, runID, template string, timeout int32) ben type benchSandbox struct { *sandbox.Sandbox - // svc and timeout let the resume step connect to the sandbox again. + // 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 { diff --git a/cmd/benchmark/snapshot.go b/cmd/benchmark/snapshot.go new file mode 100644 index 0000000..0fd1e78 --- /dev/null +++ b/cmd/benchmark/snapshot.go @@ -0,0 +1,298 @@ +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) + }}, + } +} + +// notAttempted fails a step that depends on one that did not succeed. +func notAttempted(reason string) error { + return errors.New("not attempted: " + 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. +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..21f1a0a --- /dev/null +++ b/cmd/benchmark/snapshot_test.go @@ -0,0 +1,293 @@ +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.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") + + copies := newRunView("run-1", "system/base", 1, 300, benchmark.Report{ + Phases: []benchmark.PhaseReport{{Phase: phaseRestore, Failed: 1}, {Phase: phaseFork, Failed: 2}}, + }) + out = render(copies) + assert.Contains(t, out, "3 restore(s) or fork(s) failed; the service may still have started some of those sandboxes.") + assert.Contains(t, out, "Clean them up with: ucloud-sandbox-cli sandbox kill --all -m benchmark=run-1") +} + +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 index cc456da..958fb1d 100644 --- a/cmd/benchmark/view.go +++ b/cmd/benchmark/view.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "strconv" + "strings" "time" "github.com/ucloud/ucloud-sandbox-cli/internal/benchmark" @@ -31,12 +32,17 @@ type runView struct { 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"` - // hideBreakdown leaves the connect/service rows out of the pretty table. - hideBreakdown bool + // 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 } // phaseView is the statistics of one phase. Its latencies cover the whole @@ -93,6 +99,7 @@ func newRunView(runID, template string, concurrency int, timeoutSec int32, r ben Phases: make([]phaseView, 0, len(r.Phases)), Errors: make([]errorView, 0, len(r.Errors)), Leaked: append([]string{}, r.Leaked...), + LeakedSnapshots: []string{}, } for _, p := range r.Phases { @@ -158,8 +165,10 @@ func (v runView) writePretty(w io.Writer) error { fmt.Fprintf(w, "Elapsed: %s, rate: %s sandbox/s\n\n", formatMs(v.ElapsedMs), strconv.FormatFloat(v.Rate, 'f', 2, 64)) - // Every phase is followed by its breakdown: the time spent obtaining HTTP - // connections (DNS, dial, TLS), and the rest, spent on the service. + // 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)} @@ -167,8 +176,8 @@ func (v runView) writePretty(w io.Writer) error { rows = append(rows, row) continue } - if v.hideBreakdown { - rows = append(rows, row.withLatency(p.latencyView)) + if !v.breakdown { + rows = append(rows, row.withLatency(p.Service)) continue } rows = append(rows, @@ -198,6 +207,7 @@ func (v runView) writePretty(w io.Writer) error { } v.writeCleanup(w) + v.writeSnapshotCleanup(w) return nil } @@ -212,16 +222,25 @@ func (v runView) writeCleanup(w io.Writer) { for _, id := range v.Leaked { fmt.Fprintf(w, " %s\n", id) } - hint = "Clean them up with" + // 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.createFailed(); failed > 0 { + 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.phaseFailed(phaseRestore) + v.phaseFailed(phaseFork); 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) @@ -235,16 +254,35 @@ func (v runView) writeCleanup(w io.Writer) { } } -// createFailed returns the number of iterations whose create failed. -func (v runView) createFailed() int { +// 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(benchmark.PhaseCreate) { + if p.Phase == string(phase) { return p.Failed } } return 0 } +// 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 { diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go index f0ec968..706186d 100644 --- a/internal/benchmark/benchmark_test.go +++ b/internal/benchmark/benchmark_test.go @@ -524,3 +524,70 @@ func TestRunStepsRunInOrderPastFailures(t *testing.T) { 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) +} diff --git a/internal/benchmark/report.go b/internal/benchmark/report.go index 46c8d2e..6cafff9 100644 --- a/internal/benchmark/report.go +++ b/internal/benchmark/report.go @@ -113,9 +113,7 @@ func buildReport( errorCounts[key]++ } - if r.Leaked { - report.Leaked = append(report.Leaked, r.SandboxID) - } + report.Leaked = append(report.Leaked, r.Leaked...) } for _, phase := range phases { diff --git a/internal/benchmark/runner.go b/internal/benchmark/runner.go index 3c81b33..8e3d217 100644 --- a/internal/benchmark/runner.go +++ b/internal/benchmark/runner.go @@ -9,6 +9,7 @@ package benchmark import ( "context" "errors" + "fmt" "sync" "time" ) @@ -40,12 +41,30 @@ type Sandbox interface { // CreateFunc creates the sandbox one iteration works on. type CreateFunc[S Sandbox] func(ctx context.Context) (S, error) -// Step is one timed operation run on the sandbox between create and kill. +// 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. @@ -72,7 +91,9 @@ type Options[S Sandbox] struct { func (o Options[S]) phases() []Phase { phases := []Phase{PhaseCreate} for _, step := range o.Steps { - phases = append(phases, step.Phase) + if !step.Untimed { + phases = append(phases, step.Phase) + } } if !o.SkipKill { phases = append(phases, PhaseKill) @@ -112,8 +133,8 @@ type IterationResult struct { // Errors lists the phases that failed, in the order they ran. Errors []PhaseError - // Leaked reports that the sandbox was created but could not be killed. - Leaked bool + // Leaked lists the sandboxes the iteration created but could not kill. + Leaked []string } // Succeeded reports whether every phase of the iteration succeeded. @@ -211,14 +232,19 @@ func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Opt result.SandboxID = sbx.ID() for _, step := range opts.Steps { - result.timePhase(ctx, step.Phase, func(ctx context.Context) error { - return step.Run(ctx, sbx) - }) + run := func(ctx context.Context) error { return step.Run(ctx, sbx) } + if step.Untimed { + result.runUntimed(ctx, step.Phase, run) + } else { + result.timePhase(ctx, step.Phase, run) + } } if !opts.SkipKill { killErr := result.timePhase(ctx, PhaseKill, sbx.Kill) - result.Leaked = killErr != nil && !errors.Is(killErr, ErrSandboxNotFound) + if killErr != nil && !errors.Is(killErr, ErrSandboxNotFound) { + result.Leaked = append(result.Leaked, result.SandboxID) + } } if result.Succeeded() { @@ -240,7 +266,7 @@ func (r *IterationResult) timePhase(ctx context.Context, phase Phase, run func(c start := time.Now() if err := run(traced); err != nil { - r.Errors = append(r.Errors, PhaseError{Phase: phase, Err: err}) + r.fail(phase, err) return err } r.Durations[phase] = time.Since(start) @@ -248,3 +274,19 @@ func (r *IterationResult) timePhase(ctx context.Context, phase Phase, run func(c return nil } + +// runUntimed runs an untimed step, recording only its error. +func (r *IterationResult) runUntimed(ctx context.Context, phase Phase, run func(context.Context) error) { + if err := run(ctx); err != nil { + r.fail(phase, err) + } +} + +// fail records the error of a phase, and the sandboxes it leaked. +func (r *IterationResult) fail(phase Phase, err error) { + r.Errors = append(r.Errors, PhaseError{Phase: phase, Err: err}) + + if leaked, ok := errors.AsType[*LeakedError](err); ok { + r.Leaked = append(r.Leaked, leaked.IDs...) + } +} From e978c1a09ef4914f86af14f19eb45d87caf6732a Mon Sep 17 00:00:00 2001 From: joohwan Date: Fri, 27 Nov 2026 11:39:14 +0800 Subject: [PATCH 5/8] feat: record per-iteration samples in benchmark JSON output Add an iterations array to the JSON report of every benchmark command, one entry per iteration that ran, ordered by seq: seq, sandbox_id, start_offset_ms, succeeded, leaked, phases: [{phase, duration_ms, connect_ms} | {phase, error}] Phases are listed in the order they ran. A failed phase carries only its error, with the sandbox ID kept; a phase never reached is left out; an untimed step shows up only when it fails; total only when every phase succeeded. start_offset_ms places each iteration on the run's timeline, so latency drift over a run can be seen. The pretty output is unchanged. To support it, IterationResult replaces its Durations and Connects maps and Errors list with one ordered Phases list, and gains Seq and Start; Run hands out sequence numbers and Report keeps the results. Also note in forkSandbox that the service copies the source's metadata to its forks, so the tag-based cleanup command reaches them too. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/benchmark_test.go | 61 +++++++++++++++ cmd/benchmark/snapshot.go | 4 + cmd/benchmark/view.go | 61 +++++++++++++++ internal/benchmark/benchmark_test.go | 111 +++++++++++++++++++++++++++ internal/benchmark/report.go | 26 ++++--- internal/benchmark/runner.go | 81 +++++++++++-------- 6 files changed, 304 insertions(+), 40 deletions(-) diff --git a/cmd/benchmark/benchmark_test.go b/cmd/benchmark/benchmark_test.go index 17ba700..59a0820 100644 --- a/cmd/benchmark/benchmark_test.go +++ b/cmd/benchmark/benchmark_test.go @@ -129,6 +129,67 @@ func TestLifecycleViewJSONEmptyListsAreArrays(t *testing.T) { 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) { diff --git a/cmd/benchmark/snapshot.go b/cmd/benchmark/snapshot.go index 0fd1e78..df602a9 100644 --- a/cmd/benchmark/snapshot.go +++ b/cmd/benchmark/snapshot.go @@ -164,6 +164,10 @@ func verifyRestored(ctx context.Context, sbx *benchSandbox) error { } // 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}) diff --git a/cmd/benchmark/view.go b/cmd/benchmark/view.go index 958fb1d..f7a48fc 100644 --- a/cmd/benchmark/view.go +++ b/cmd/benchmark/view.go @@ -40,6 +40,10 @@ type runView struct { // 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 @@ -77,6 +81,58 @@ func newLatencyView(s benchmark.Stats) latencyView { } } +// 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"` @@ -100,6 +156,7 @@ func newRunView(runID, template string, concurrency int, timeoutSec int32, r ben 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 { @@ -117,6 +174,10 @@ func newRunView(runID, template string, concurrency int, timeoutSec int32, r ben 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)) + } + return v } diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go index 706186d..dafb1e3 100644 --- a/internal/benchmark/benchmark_test.go +++ b/internal/benchmark/benchmark_test.go @@ -312,6 +312,7 @@ func TestRunCancelStopsNewIterationsAndCleansUp(t *testing.T) { 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) @@ -591,3 +592,113 @@ func TestRunLeaksBothStepAndKillFailures(t *testing.T) { 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") +} diff --git a/internal/benchmark/report.go b/internal/benchmark/report.go index 6cafff9..b6b9cf8 100644 --- a/internal/benchmark/report.go +++ b/internal/benchmark/report.go @@ -29,6 +29,10 @@ type Report struct { // 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 @@ -96,17 +100,17 @@ func buildReport( failed[PhaseTotal]++ } - for phase, d := range r.Durations { - connect := r.Connects[phase] - samples[phase] = append(samples[phase], d) - connects[phase] = append(connects[phase], connect) - services[phase] = append(services[phase], d-connect) - } + 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 + } - for _, e := range r.Errors { - failed[e.Phase]++ + failed[p.Phase]++ - key := errorKey{phase: e.Phase, message: normalizeMessage(e.Err.Error(), r.SandboxID)} + key := errorKey{phase: p.Phase, message: normalizeMessage(p.Err.Error(), r.SandboxID)} if errorCounts[key] == 0 { errorOrder = append(errorOrder, key) } @@ -140,6 +144,10 @@ func buildReport( 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 } diff --git a/internal/benchmark/runner.go b/internal/benchmark/runner.go index 8e3d217..fa16e04 100644 --- a/internal/benchmark/runner.go +++ b/internal/benchmark/runner.go @@ -112,26 +112,36 @@ type Progress struct { Failed int } -// PhaseError is the failure of one phase of an iteration. -type PhaseError struct { +// PhaseResult is the outcome of one phase of an iteration. +type PhaseResult struct { Phase Phase - Err error + + // 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 { - SandboxID string + // Seq numbers the iterations from 1 in the order they were handed out. + Seq int - // Durations holds the time taken by every phase that succeeded. - Durations map[Phase]time.Duration + // Start is when the iteration started, as an offset from the start of + // the run. + Start time.Duration - // Connects holds, for every phase in Durations, the part of its time spent - // obtaining HTTP connections (DNS, dial, TLS). The rest is the time the - // service took to respond. - Connects map[Phase]time.Duration + SandboxID string - // Errors lists the phases that failed, in the order they ran. - Errors []PhaseError + // 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 @@ -139,7 +149,12 @@ type IterationResult struct { // Succeeded reports whether every phase of the iteration succeeded. func (r IterationResult) Succeeded() bool { - return len(r.Errors) == 0 + 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 @@ -155,7 +170,7 @@ func Run[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) // In-flight iterations must be able to clean up after a cancellation. iterCtx := context.WithoutCancel(ctx) - jobs := make(chan struct{}) + jobs := make(chan int) var ( mu sync.Mutex results = make([]IterationResult, 0, count) @@ -167,14 +182,14 @@ func Run[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) for range concurrency { wg.Go(func() { - for range jobs { + 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) + result := runIteration(iterCtx, create, opts, seq, start) mu.Lock() results = append(results, result) @@ -193,11 +208,11 @@ func Run[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) } dispatch: - for range count { + for seq := 1; seq <= count; seq++ { select { case <-ctx.Done(): break dispatch - case jobs <- struct{}{}: + case jobs <- seq: } } close(jobs) @@ -211,15 +226,17 @@ dispatch: } // runIteration creates a sandbox, runs every step on it and kills it. The -// sandbox is killed even when a step fails. -func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Options[S]) IterationResult { +// 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{ - Durations: make(map[Phase]time.Duration, len(opts.Steps)+3), - Connects: make(map[Phase]time.Duration, len(opts.Steps)+3), + Seq: seq, + Start: iterStart.Sub(runStart), + Phases: make([]PhaseResult, 0, len(opts.Steps)+3), } - iterStart := time.Now() - var sbx S err := result.timePhase(ctx, PhaseCreate, func(ctx context.Context) error { var err error @@ -249,11 +266,14 @@ func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Opt if result.Succeeded() { var connect time.Duration - for _, d := range result.Connects { - connect += d + for _, p := range result.Phases { + connect += p.Connect } - result.Durations[PhaseTotal] = time.Since(iterStart) - result.Connects[PhaseTotal] = connect + result.Phases = append(result.Phases, PhaseResult{ + Phase: PhaseTotal, + Duration: time.Since(iterStart), + Connect: connect, + }) } return result @@ -269,8 +289,7 @@ func (r *IterationResult) timePhase(ctx context.Context, phase Phase, run func(c r.fail(phase, err) return err } - r.Durations[phase] = time.Since(start) - r.Connects[phase] = conn.Total() + r.Phases = append(r.Phases, PhaseResult{Phase: phase, Duration: time.Since(start), Connect: conn.Total()}) return nil } @@ -284,7 +303,7 @@ func (r *IterationResult) runUntimed(ctx context.Context, phase Phase, run func( // fail records the error of a phase, and the sandboxes it leaked. func (r *IterationResult) fail(phase Phase, err error) { - r.Errors = append(r.Errors, PhaseError{Phase: phase, Err: err}) + 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...) From 1dd0514e7586e1114905d8ebc3d49cdaebf5aae4 Mon Sep 17 00:00:00 2001 From: joohwan Date: Fri, 27 Nov 2026 11:39:14 +0800 Subject: [PATCH 6/8] chore: ignore .idea directory Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) 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 From a446df2c7b2f8bfaf82dc706af8da150881fb8f4 Mon Sep 17 00:00:00 2001 From: joohwan Date: Fri, 27 Nov 2026 15:12:09 +0800 Subject: [PATCH 7/8] feat: check the intranet over HTTP and take the region from the domain Replace the health benchmark's intranet ping with a curl probe. Any HTTP response counts as reaching the service, since the region's US3 endpoint answers an anonymous request with 400; the check then measures what sandboxes actually do, needs neither sudo nor ping, and reports how far a failed request got (resolved, connected, first byte), so a slow name lookup can be told from a connection that never came. --intranet-url replaces --intranet-host and defaults to https://internal.s3-.ufileos.com/. ResolveRegion reads the region from a ".sandbox.ucloudai.com" domain, which the API prefers over the region, and reports when it cannot tell: the intranet check then asks for --intranet-url instead of probing another region's endpoint. A custom domain names no region, and the flag is not needed when the check is skipped. health's scratch file paths are fixed rather than random, so the same failure groups into one report row, and a step that never ran is marked with the new errNotAttempted sentinel, so it is not taken for a request that failed. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/health.go | 149 +++++++++++++++++++++------------ cmd/benchmark/health_test.go | 99 +++++++++++++++------- cmd/benchmark/snapshot.go | 6 +- internal/config/config.go | 22 +++-- internal/config/config_test.go | 24 +++++- 5 files changed, 209 insertions(+), 91 deletions(-) diff --git a/cmd/benchmark/health.go b/cmd/benchmark/health.go index d753a31..f96cdd5 100644 --- a/cmd/benchmark/health.go +++ b/cmd/benchmark/health.go @@ -10,6 +10,7 @@ import ( "net/http" "net/url" "slices" + "strconv" "strings" "time" @@ -29,9 +30,9 @@ const ( phaseResume benchmark.Phase = "resume" ) -// intranetHostTemplate builds a region's internal US3 (ufile) endpoint, the -// host its sandboxes should reach over the intranet. -const intranetHostTemplate = "internal.s3-%s.ufileos.com" +// 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. @@ -67,7 +68,7 @@ type healthOperation struct { runOptions urls []string - intranetHost string + intranetURL string publicURLPort int skip []string @@ -84,8 +85,8 @@ func (o *healthOperation) Command() *cobra.Command { 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.intranetHost, "intranet-host", "", "", - "Intranet host the sandbox must reach by ping (default: the region's internal US3 endpoint)") + 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") @@ -102,8 +103,7 @@ func (o *healthOperation) validate() error { } seen := make(map[string]bool, len(o.urls)) for _, raw := range o.urls { - u, err := url.Parse(raw) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + 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. @@ -112,6 +112,9 @@ func (o *healthOperation) validate() error { } 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) } @@ -131,6 +134,12 @@ func (o *healthOperation) validate() error { 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 { @@ -149,29 +158,42 @@ func (o *healthOperation) Run(ctx cmd.OperationContext) error { return err } - intranetHost := resolveIntranetHost(config.ResolveRegion(ctx.Config), o.intranetHost) + intranetURL, err := o.resolveIntranetURL(ctx.Config) + if err != nil { + return err + } return o.run(ctx, sdk, runSpec{ name: "health", - steps: o.steps(sdk.Transport(), intranetHost), + steps: o.steps(sdk.Transport(), intranetURL), }) } -// resolveIntranetHost returns the intranet host to check: the one given by -// flag, or the region's own US3 endpoint. -func resolveIntranetHost(region, override string) string { - if override != "" { - return override +// 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(intranetHostTemplate, region) + 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, intranetHost string) []benchmark.Step[*benchSandbox] { +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)) @@ -182,7 +204,7 @@ func (o *healthOperation) steps(t *transport.Client, intranetHost string) []benc "exec": {execStep("echo ok", "")}, "filesystem": {{Phase: phaseFilesystem, Run: checkFilesystem}}, "internet": internet, - "intranet": {pingStep(benchmark.Phase("intranet "+intranetHost), intranetHost)}, + "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) }}}, @@ -203,9 +225,13 @@ func (o *healthOperation) steps(t *transport.Client, intranetHost string) []benc // 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() - path := "/tmp/ucloud-sandbox-health-" + token + const path = "/tmp/ucloud-sandbox-health" fs := sbx.Files() if _, err := fs.Write(ctx, path, token); err != nil { @@ -264,51 +290,67 @@ func checkHTTPCode(stdout string) error { } } -// pingStep checks that the sandbox reaches host with ICMP echo: the name has -// to resolve and at least one of the pings has to be answered. -func pingStep(phase benchmark.Phase, host string) benchmark.Step[*benchSandbox] { +// 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 { - result, err := sbx.run(ctx, pingCommand(host), "") - if err == nil { - return nil - } - // A ping nobody answers explains itself on stdout, in the packet - // loss summary, and leaves stderr empty. + // A failed command still comes with what curl printed. + result, err := sbx.run(ctx, intranetProbeCommand(target), "") + var code, timeline string if result != nil { - if summary := pingSummary(result.Stdout); summary != "" && strings.TrimSpace(result.Stderr) == "" { - return fmt.Errorf("ping %s: %s", host, summary) - } + code, timeline = parseIntranetProbe(result.Stdout) + } + if timeline != "" { + timeline = " (" + timeline + ")" } - return fmt.Errorf("ping %s: %w", host, err) + 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 }, } } -// pingCount and pingWaitSec shape the intranet ping: how many echo requests -// are sent, and how many seconds each one waits for its reply. -const ( - pingCount = 3 - pingWaitSec = 2 -) - -// pingCommand returns the ping invocation checking host. ping exits 0 once -// any reply arrives and non-zero when none does. It runs through sudo, since -// the sandbox's default user may not be allowed to send ICMP; -n makes sudo -// fail at once rather than wait for a password nobody will type. -func pingCommand(host string) string { - return fmt.Sprintf("sudo -n ping -c %d -W %d %s", pingCount, pingWaitSec, shellQuote(host)) +// 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)) } -// pingSummary returns the packet loss line of ping's output, or "". -func pingSummary(stdout string) string { - for line := range strings.SplitSeq(stdout, "\n") { - if strings.Contains(line, "packet loss") { - return strings.TrimSpace(line) +// 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 "" + return fields[0], strings.Join(parts, ", ") } // shellQuote quotes s as a single word for the shell envd runs commands in. @@ -321,7 +363,8 @@ func shellQuote(s string) string { // `sandbox host` reports, checking the gateway's inbound path. func checkPublicURL(ctx context.Context, t *transport.Client, sbx *benchSandbox, port int) error { token := randomToken() - dir := "/tmp/ucloud-sandbox-health-www-" + token + // 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) @@ -430,7 +473,7 @@ func checkPause(ctx context.Context, sbx *benchSandbox) error { // 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 errors.New("not attempted: the sandbox did not pause") + return notAttempted("the sandbox did not pause") } resumed, err := sbx.svc.Connect(ctx, sbx.ID(), api.ConnectSandbox{Timeout: sbx.timeout}) diff --git a/cmd/benchmark/health_test.go b/cmd/benchmark/health_test.go index 22dfbf5..55ed5af 100644 --- a/cmd/benchmark/health_test.go +++ b/cmd/benchmark/health_test.go @@ -9,6 +9,7 @@ import ( "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 { @@ -24,7 +25,7 @@ func TestHealthDefaults(t *testing.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.intranetHost, "resolved from the region") + assert.Empty(t, op.intranetURL, "resolved from the region") assert.Equal(t, 8000, op.publicURLPort) assert.NoError(t, op.validate()) } @@ -41,6 +42,7 @@ func TestHealthValidate(t *testing.T) { {"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) { @@ -54,22 +56,22 @@ func TestHealthValidate(t *testing.T) { 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 TestResolveIntranetHost(t *testing.T) { - assert.Equal(t, "internal.s3-cn-wlcb.ufileos.com", resolveIntranetHost("cn-wlcb", "")) - assert.Equal(t, "internal.s3-cn-sh2.ufileos.com", resolveIntranetHost("cn-sh", "")) - assert.Equal(t, "internal.s3-us-ca.ufileos.com", resolveIntranetHost("us-ca", "")) - assert.Equal(t, "internal.s3-us-den.ufileos.com", resolveIntranetHost("us-den", "")) - assert.Equal(t, "internal.s3-vn-sng.ufileos.com", resolveIntranetHost("vn-sng", "")) +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, "internal.s3-mars-1.ufileos.com", resolveIntranetHost("mars-1", ""), + assert.Equal(t, "https://internal.s3-mars-1.ufileos.com/", intranetURLFor("mars-1"), "a new region follows the naming pattern") - assert.Equal(t, "10.0.0.1", resolveIntranetHost("cn-wlcb", "10.0.0.1"), "the flag wins") - assert.Equal(t, "10.0.0.1", resolveIntranetHost("mars-1", "10.0.0.1")) } func TestHealthSteps(t *testing.T) { @@ -87,11 +89,11 @@ func TestHealthSteps(t *testing.T) { "filesystem", "internet https://www.baidu.com", "internet https://example.com/path", - "intranet internal.s3-cn-wlcb.ufileos.com", + "intranet https://internal.s3-cn-wlcb.ufileos.com/", "public-url 8000", "pause", "resume", - }, phases(op.steps(nil, "internal.s3-cn-wlcb.ufileos.com"))) + }, phases(op.steps(nil, "https://internal.s3-cn-wlcb.ufileos.com/"))) } func TestProbeCommand(t *testing.T) { @@ -103,21 +105,34 @@ func TestProbeCommand(t *testing.T) { probeCommand("http://x/'; rm -rf /"), "a quote in the URL cannot break out") } -func TestPingCommand(t *testing.T) { - assert.Equal(t, "sudo -n ping -c 3 -W 2 'internal.s3-cn-wlcb.ufileos.com'", pingCommand("internal.s3-cn-wlcb.ufileos.com")) - assert.Equal(t, `sudo -n ping -c 3 -W 2 'x'"'"'; rm -rf /'`, pingCommand("x'; rm -rf /"), - "a quote in the host 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 TestPingSummary(t *testing.T) { - out := `PING internal-cn-wlcb.ufileos.com (10.0.0.1) 56(84) bytes of data. - ---- internal-cn-wlcb.ufileos.com ping statistics --- -3 packets transmitted, 0 received, 100% packet loss, time 2034ms -` - assert.Equal(t, "3 packets transmitted, 0 received, 100% packet loss, time 2034ms", pingSummary(out)) - assert.Empty(t, pingSummary("ping: unknown host")) - assert.Empty(t, pingSummary("")) +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) { @@ -170,17 +185,17 @@ func healthPhases(t *testing.T, args ...string) []benchmark.Phase { op := parseHealth(t, args...) require.NoError(t, op.validate()) var out []benchmark.Phase - for _, s := range op.steps(nil, "internal.s3-cn-wlcb.ufileos.com") { + 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 internal.s3-cn-wlcb.ufileos.com"}, + 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 internal.s3-cn-wlcb.ufileos.com"}, + 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") @@ -188,7 +203,7 @@ func TestHealthSelectChecks(t *testing.T) { "pause covers resume") assert.Equal(t, []benchmark.Phase{ - "exec", "filesystem", "internet " + defaultInternetURL, "intranet internal.s3-cn-wlcb.ufileos.com", + "exec", "filesystem", "internet " + defaultInternetURL, "intranet https://internal.s3-cn-wlcb.ufileos.com/", }, healthPhases(t, "--skip", "pause,public-url")) } @@ -216,3 +231,29 @@ 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/snapshot.go b/cmd/benchmark/snapshot.go index df602a9..da61f81 100644 --- a/cmd/benchmark/snapshot.go +++ b/cmd/benchmark/snapshot.go @@ -115,9 +115,13 @@ func snapshotSteps(leaked *idList) []benchmark.Step[*benchSandbox] { } } +// 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 errors.New("not attempted: " + reason) + return fmt.Errorf("%w: %s", errNotAttempted, reason) } // writeToken leaves a random token in the sandbox for the copies to carry. diff --git a/internal/config/config.go b/internal/config/config.go index a8de9b7..63d92aa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -15,7 +15,8 @@ import ( const ( defaultRegion = "cn-wlcb" defaultDomain = defaultRegion + ".sandbox.ucloudai.com" - domainTemplate = "%s.sandbox.ucloudai.com" + domainSuffix = ".sandbox.ucloudai.com" + domainTemplate = "%s" + domainSuffix configDir = ".ucloud-sandbox-cli" configFile = "config.json" @@ -162,13 +163,22 @@ func resolveDomain(cfg *Config) string { return defaultDomain } -// ResolveRegion returns the configured region, or the default one when none -// is set. -func ResolveRegion(cfg *Config) string { +// 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 + return cfg.Region, true } - return defaultRegion + return defaultRegion, true } // NewClient validates the config and creates a sandbox client. Each modifier diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 80fd8c7..36845e5 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -241,6 +241,26 @@ func TestNewClient_AppliesModifiers(t *testing.T) { } func TestResolveRegion(t *testing.T) { - assert.Equal(t, "cn-wlcb", ResolveRegion(&Config{}), "default region") - assert.Equal(t, "us-ca", ResolveRegion(&Config{Region: "us-ca"})) + 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) + }) + } } From 3af2f81a58702b915c083b8361910df83fc9d2ac Mon Sep 17 00:00:00 2001 From: joohwan Date: Fri, 27 Nov 2026 15:12:23 +0800 Subject: [PATCH 8/8] feat: add --output to benchmark commands and tidy their reports -o/--output writes the JSON report to a file whatever --format prints, so one run can show its table and keep its samples; previously the two were mutually exclusive, and running twice to get both compared two different runs. The path is checked before the run starts and the file is written after the report is printed, so a wrong path costs neither the run nor its results. Grouped error messages drop the request URL net/http puts in front of the cause for any verb, kill's DELETE included, so long URLs no longer push the cause off the end of the message column. Untimed steps' connection setup now counts toward total's connect rather than its service time. A run that finishes in the same instant its context is cancelled no longer prints the interrupted banner: the watcher checks whether the run already finished before announcing anything. Tables say whether they show service or full latency, restore and fork failures that never sent a request no longer claim a sandbox may have been started, and checkResume uses the notAttempted sentinel. Co-Authored-By: Claude Opus 5.5 --- cmd/benchmark/benchmark_test.go | 104 ++++++++++++++++++++++++++- cmd/benchmark/run.go | 55 +++++++++++--- cmd/benchmark/snapshot_test.go | 21 +++++- cmd/benchmark/view.go | 59 ++++++++++++++- internal/benchmark/benchmark_test.go | 43 +++++++++-- internal/benchmark/report.go | 16 ++++- internal/benchmark/runner.go | 18 +++-- 7 files changed, 290 insertions(+), 26 deletions(-) diff --git a/cmd/benchmark/benchmark_test.go b/cmd/benchmark/benchmark_test.go index 59a0820..01f66fd 100644 --- a/cmd/benchmark/benchmark_test.go +++ b/cmd/benchmark/benchmark_test.go @@ -6,6 +6,8 @@ import ( "errors" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "sync/atomic" "testing" @@ -203,6 +205,7 @@ func TestLifecycleViewPretty(t *testing.T) { 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 |") @@ -225,8 +228,105 @@ func TestRunViewShowsServiceTimeByDefault(t *testing.T) { // 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.NotContains(t, out, "connect") - assert.NotContains(t, out, "service") + 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) { diff --git a/cmd/benchmark/run.go b/cmd/benchmark/run.go index 9c23aeb..580aa68 100644 --- a/cmd/benchmark/run.go +++ b/cmd/benchmark/run.go @@ -37,6 +37,7 @@ type runOptions struct { concurrency int timeout int32 format string + output string breakdown bool } @@ -49,6 +50,8 @@ func (o *runOptions) addFlags(c *cobra.Command, defaultCount int, timeoutUsage s 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") } @@ -104,18 +107,18 @@ func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runS // 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 is closed before the deferred stop runs, so a run - // that ends normally is not reported as interrupted. + // process out. finished := make(chan struct{}) defer close(finished) - go func() { - select { - case <-runCtx.Done(): - stop() - fmt.Fprintf(os.Stderr, "\nInterrupted: waiting for in-flight iterations to finish (Ctrl+C again to force quit, then clean up with: %s)...\n", cleanup) - case <-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) @@ -155,9 +158,43 @@ func (o *runOptions) run(ctx cmd.OperationContext, sdk *client.Client, spec runS 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. diff --git a/cmd/benchmark/snapshot_test.go b/cmd/benchmark/snapshot_test.go index 21f1a0a..3782660 100644 --- a/cmd/benchmark/snapshot_test.go +++ b/cmd/benchmark/snapshot_test.go @@ -200,6 +200,7 @@ func TestSnapshotStepsNotAttempted(t *testing.T) { 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") @@ -267,12 +268,28 @@ func TestRunViewSnapshotCleanup(t *testing.T) { 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: 1}, {Phase: phaseFork, Failed: 2}}, + 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.") + 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) { diff --git a/cmd/benchmark/view.go b/cmd/benchmark/view.go index f7a48fc..1705e7b 100644 --- a/cmd/benchmark/view.go +++ b/cmd/benchmark/view.go @@ -1,8 +1,12 @@ package benchmark import ( + "encoding/json" + "errors" "fmt" "io" + "os" + "slices" "strconv" "strings" "time" @@ -47,6 +51,10 @@ type runView struct { // 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 @@ -178,6 +186,8 @@ func newRunView(runID, template string, concurrency int, timeoutSec int32, r ben v.Iterations = append(v.Iterations, newIterationView(it)) } + v.copyStartsFailed = failedRequests(r.Iterations, phaseRestore, phaseFork) + return v } @@ -214,6 +224,30 @@ type errorRow struct { 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" @@ -226,6 +260,14 @@ func (v runView) writePretty(w io.Writer) error { 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 @@ -297,7 +339,7 @@ func (v runView) writeCleanup(w io.Writer) { } // Restoring and forking start sandboxes too, the same way. - if failed := v.phaseFailed(phaseRestore) + v.phaseFailed(phaseFork); failed > 0 { + 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" } @@ -325,6 +367,21 @@ func (v runView) phaseFailed(phase benchmark.Phase) int { 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) { diff --git a/internal/benchmark/benchmark_test.go b/internal/benchmark/benchmark_test.go index dafb1e3..83c2cbf 100644 --- a/internal/benchmark/benchmark_test.go +++ b/internal/benchmark/benchmark_test.go @@ -469,13 +469,25 @@ func TestOptionsPhases(t *testing.T) { func TestNormalizeMessage(t *testing.T) { assert.Equal(t, "command exited with code 127: bash: nope: command not found", - normalizeMessage("command exited with code 127: bash: nope: command not found\n", "sbx-1")) + normalizeMessage(errors.New("command exited with code 127: bash: nope: command not found\n"), "sbx-1")) assert.Equal(t, "line one line two", - normalizeMessage(" line one\n\tline two\r\n", "")) + normalizeMessage(errors.New(" line one\n\tline two\r\n"), "")) assert.Equal(t, - `Post "https://49983-.example.com/process.Process/Start": dial tcp: i/o timeout`, - normalizeMessage(`Post "https://49983-ibx7k2.example.com/process.Process/Start": dial tcp: i/o timeout`, "ibx7k2")) + "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) { @@ -702,3 +714,26 @@ func TestRunRecordsUntimedStepOnlyWhenItFails(t *testing.T) { 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/report.go b/internal/benchmark/report.go index b6b9cf8..aae9f3e 100644 --- a/internal/benchmark/report.go +++ b/internal/benchmark/report.go @@ -2,6 +2,7 @@ package benchmark import ( "cmp" + "regexp" "slices" "strings" "time" @@ -110,7 +111,7 @@ func buildReport( failed[p.Phase]++ - key := errorKey{phase: p.Phase, message: normalizeMessage(p.Err.Error(), r.SandboxID)} + key := errorKey{phase: p.Phase, message: normalizeMessage(p.Err, r.SandboxID)} if errorCounts[key] == 0 { errorOrder = append(errorOrder, key) } @@ -154,12 +155,21 @@ func buildReport( // 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 -// iteration's sandbox ID, which turns up in hosts such as +// 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(msg, sandboxID string) string { +func normalizeMessage(err error, sandboxID string) string { + msg := urlErrorPattern.ReplaceAllString(err.Error(), "") if sandboxID != "" { msg = strings.ReplaceAll(msg, sandboxID, sandboxPlaceholder) } diff --git a/internal/benchmark/runner.go b/internal/benchmark/runner.go index fa16e04..2e5039b 100644 --- a/internal/benchmark/runner.go +++ b/internal/benchmark/runner.go @@ -248,10 +248,15 @@ func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Opt } 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 { - result.runUntimed(ctx, step.Phase, run) + untimedConnect += result.runUntimed(ctx, step.Phase, run) } else { result.timePhase(ctx, step.Phase, run) } @@ -265,7 +270,7 @@ func runIteration[S Sandbox](ctx context.Context, create CreateFunc[S], opts Opt } if result.Succeeded() { - var connect time.Duration + connect := untimedConnect for _, p := range result.Phases { connect += p.Connect } @@ -294,11 +299,14 @@ func (r *IterationResult) timePhase(ctx context.Context, phase Phase, run func(c return nil } -// runUntimed runs an untimed step, recording only its error. -func (r *IterationResult) runUntimed(ctx context.Context, phase Phase, run func(context.Context) error) { - if err := run(ctx); err != 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.