diff --git a/pkg/cmd/gpucreate/gpucreate.go b/pkg/cmd/gpucreate/gpucreate.go index 1cc9b9c4..d8c8ec2a 100644 --- a/pkg/cmd/gpucreate/gpucreate.go +++ b/pkg/cmd/gpucreate/gpucreate.go @@ -79,7 +79,14 @@ You can attach a startup script that runs when the instance boots using the --startup-script flag. The script can be provided as: - An inline string: --startup-script 'pip install torch' - A file path (prefix with @): --startup-script @setup.sh - - An absolute file path: --startup-script @/path/to/setup.sh` + - An absolute file path: --startup-script @/path/to/setup.sh + +Location: +By default each type is created in its catalog default location, shown in the +LOCATION column of 'brev search' and in --dry-run output. Use --location (and +optionally --sub-location) to choose one; types that are not available there +are skipped. 'brev search locations' lists locations, and +'brev search --location' lists the types available in one.` example = ` # Create an instance using smart defaults (sorted by price) @@ -88,6 +95,9 @@ You can attach a startup script that runs when the instance boots using the # Create with a specific GPU type brev create my-instance --type g5.xlarge + # Create in a specific location and zone + brev create my-cpu --type n2d-standard-2 --location us-west2 --sub-location us-west2-a + # Try multiple types in order (fallback chain) brev create my-instance --type g5.xlarge,g5.2xlarge,g4dn.xlarge @@ -150,6 +160,11 @@ type searchFilterFlags struct { flexPorts bool sortBy string descending bool + + // Placement, not a type filter, except that auto-selection only + // considers types available in location. + location string + subLocation string } // hasUserFilters returns true if the user specified any search filter flags @@ -232,6 +247,10 @@ func NewCmdGPUCreate(t *terminal.Terminal, gpuCreateStore GPUCreateStore) *cobra return err } + if filters.subLocation != "" && filters.location == "" { + return breverrors.NewValidationError("--sub-location requires --location") + } + types, err := parseInstanceTypes(instanceTypes, readStdin, os.Stdin) if err != nil { return breverrors.WrapAndTrace(err) @@ -258,15 +277,18 @@ func NewCmdGPUCreate(t *terminal.Terminal, gpuCreateStore GPUCreateStore) *cobra LaunchableID: launchableID, LaunchableInfo: launchableInfo, ParameterBindings: parameterBindings, + Location: filters.location, + SubLocation: filters.subLocation, } - opts.InstanceTypes, err = resolveInstanceTypes(cmd, gpuCreateStore, opts, types, &filters) + var catalog []gpusearch.InstanceType + opts.InstanceTypes, catalog, err = resolveInstanceTypes(cmd, gpuCreateStore, opts, types, &filters) if err != nil { return err } if dryRun { - return runDryRun(t, gpuCreateStore, opts.InstanceTypes, &filters) + return runDryRun(t, gpuCreateStore, opts, catalog) } return RunGPUCreate(cmd.Context(), t, gpuCreateStore, opts) @@ -309,6 +331,8 @@ func registerCreateFlags(cmd *cobra.Command, name, instanceTypes *string, readSt cmd.Flags().StringVarP(launchable, "launchable", "l", "", "Launchable ID or URL to deploy (e.g., env-XXX or console URL)") cmd.Flags().StringArrayVar(launchableParams, "param", nil, "Launchable setup value NAME=VALUE (repeatable)") + cmd.Flags().StringVar(&filters.location, "location", "", "Location to create the instance in (e.g., us-west2; see 'brev search locations')") + cmd.Flags().StringVar(&filters.subLocation, "sub-location", "", "Zone within --location (e.g., us-west2-a)") cmd.Flags().StringVarP(&filters.gpuName, "gpu-name", "g", "", "Filter by GPU name (e.g., A100, H100)") cmd.Flags().StringVar(&filters.provider, "provider", "", "Filter by provider/cloud (e.g., aws, gcp)") cmd.Flags().Float64VarP(&filters.minVRAM, "min-vram", "v", 0, "Minimum VRAM per GPU in GB") @@ -346,6 +370,22 @@ type GPUCreateOptions struct { LaunchableID string LaunchableInfo *store.LaunchableResponse // populated when LaunchableID is set ParameterBindings []store.ParameterBinding + Location string // explicit override; empty preserves launchable or server placement + SubLocation string +} + +// requestedPlacement applies flag overrides to saved launchable placement. +// An empty result leaves placement to the server; previews can show the catalog default. +func (opts GPUCreateOptions) requestedPlacement() (string, string) { + if opts.Location != "" { + // A saved zone belongs to the launchable's location, so never inherit it. + return opts.Location, opts.SubLocation + } + if opts.LaunchableID != "" && opts.LaunchableInfo != nil { + request := opts.LaunchableInfo.CreateWorkspaceRequest + return request.Location, request.SubLocation + } + return "", "" } // parseLaunchableID extracts a launchable ID from either a raw ID (env-XXX) or @@ -632,30 +672,30 @@ func launchableBuildModeName(info *store.LaunchableResponse) string { } // resolveInstanceTypes determines instance types from launchable, flags, or filters -func resolveInstanceTypes(cmd *cobra.Command, gpuCreateStore GPUCreateStore, opts GPUCreateOptions, types []InstanceSpec, filters *searchFilterFlags) ([]InstanceSpec, error) { +func resolveInstanceTypes(cmd *cobra.Command, gpuCreateStore GPUCreateStore, opts GPUCreateOptions, types []InstanceSpec, filters *searchFilterFlags) ([]InstanceSpec, []gpusearch.InstanceType, error) { if opts.LaunchableID != "" && len(types) == 0 && !cmd.Flags().Changed("type") { instanceType := "" if opts.LaunchableInfo != nil { instanceType = opts.LaunchableInfo.CreateWorkspaceRequest.InstanceType } if instanceType != "" { - return []InstanceSpec{{Type: instanceType}}, nil + return []InstanceSpec{{Type: instanceType}}, nil, nil } - return nil, breverrors.NewValidationError("launchable has no instance type configured and no --type was specified") + return nil, nil, breverrors.NewValidationError("launchable has no instance type configured and no --type was specified") } if len(types) == 0 { - filtered, err := getFilteredInstanceTypes(gpuCreateStore, filters) + filtered, catalog, err := getFilteredInstanceTypes(gpuCreateStore, filters) if err != nil { - return nil, breverrors.WrapAndTrace(err) + return nil, nil, breverrors.WrapAndTrace(err) } if len(filtered) == 0 { - return nil, breverrors.NewValidationError("no GPU instances match the specified filters. Try 'brev search' to see available options") + return nil, nil, breverrors.NewValidationError("no GPU instances match the specified filters. Try 'brev search' to see available options") } - return filtered, nil + return filtered, catalog, nil } - return types, nil + return types, nil, nil } // parseStartupScript parses the startup script from a string or file path @@ -679,15 +719,16 @@ func parseStartupScript(value string) (string, error) { return value, nil } -// searchInstances fetches and filters GPU instances using user-provided filters merged with defaults -func searchInstances(s GPUCreateStore, filters *searchFilterFlags) ([]gpusearch.GPUInstanceInfo, float64, error) { - response, err := s.GetInstanceTypes(false) +// getFilteredInstanceTypes selects GPU types and returns the catalog for placement previews. +func getFilteredInstanceTypes(s GPUCreateStore, filters *searchFilterFlags) ([]InstanceSpec, []gpusearch.InstanceType, error) { + // Same catalog as 'brev search gpu'; CPU types are filtered out below. + response, err := s.GetInstanceTypes(true) if err != nil { - return nil, 0, breverrors.WrapAndTrace(err) + return nil, nil, breverrors.WrapAndTrace(err) } if response == nil || len(response.Items) == 0 { - return nil, 0, nil + return nil, nil, nil } minTotalVRAM := orDefault(filters.minTotalVRAM, defaultMinTotalVRAM) @@ -705,19 +746,9 @@ func searchInstances(s GPUCreateStore, filters *searchFilterFlags) ([]gpusearch. instances := gpusearch.ProcessInstances(response.Items) filtered := gpusearch.FilterInstances(instances, filters.gpuName, filters.provider, "", filters.minVRAM, minTotalVRAM, minCapability, 0, minDisk, 0, maxBootTime, filters.stoppable, filters.rebootable, filters.flexPorts, true) + filtered = gpusearch.FilterByLocation(filtered, filters.location) gpusearch.SortInstances(filtered, sortBy, filters.descending) - return filtered, minDisk, nil -} - -// getFilteredInstanceTypes fetches GPU instance types using user-provided filters -// merged with defaults. When a filter flag is not set, the default value is used. -func getFilteredInstanceTypes(s GPUCreateStore, filters *searchFilterFlags) ([]InstanceSpec, error) { - filtered, minDisk, err := searchInstances(s, filters) - if err != nil { - return nil, breverrors.WrapAndTrace(err) - } - var specs []InstanceSpec for _, inst := range filtered { diskGB := inst.DiskMin @@ -727,25 +758,21 @@ func getFilteredInstanceTypes(s GPUCreateStore, filters *searchFilterFlags) ([]I specs = append(specs, InstanceSpec{Type: inst.Type, DiskGB: diskGB}) } - return specs, nil + return specs, response.Items, nil } // runDryRun shows the instance types that would be used without creating anything -func runDryRun(t *terminal.Terminal, s GPUCreateStore, specs []InstanceSpec, filters *searchFilterFlags) error { - if len(specs) > 0 { - t.Print(formatInstanceSpecs(specs)) - return nil - } - - filtered, _, err := searchInstances(s, filters) - if err != nil { - return breverrors.WrapAndTrace(err) - } - - piped := gpusearch.IsStdoutPiped() - if err := gpusearch.DisplayGPUResults(t, filtered, false, piped, false); err != nil { - return breverrors.WrapAndTrace(err) +func runDryRun(t *terminal.Terminal, s GPUCreateStore, opts GPUCreateOptions, catalog []gpusearch.InstanceType) error { + if catalog == nil { + response, err := s.GetInstanceTypes(true) + if err != nil { + return breverrors.WrapAndTrace(err) + } + if response != nil { + catalog = response.Items + } } + t.Print(formatInstanceSpecs(opts.InstanceTypes, catalog, opts)) return nil } @@ -912,19 +939,66 @@ func isValidInstanceType(s string) bool { return hasLetter && hasDigit } -// formatInstanceSpecs formats a slice of InstanceSpec for display -func formatInstanceSpecs(specs []InstanceSpec) string { +// formatInstanceSpecs formats specs for display, including where each type +// will be created when the catalog or the requested location says so. +func formatInstanceSpecs(specs []InstanceSpec, catalog []gpusearch.InstanceType, opts GPUCreateOptions) string { + location, subLocation := opts.requestedPlacement() var parts []string for _, spec := range specs { + var details []string if spec.DiskGB > 0 { - parts = append(parts, fmt.Sprintf("%s (%.0fGB disk)", spec.Type, spec.DiskGB)) - } else { + details = append(details, fmt.Sprintf("%.0fGB disk", spec.DiskGB)) + } + if placement, err := resolvePlacement(catalog, spec.Type, location, subLocation); err != nil { + details = append(details, "not available in "+location) + } else if placement != "" { + details = append(details, "location: "+placement) + } + if len(details) == 0 { parts = append(parts, spec.Type) + } else { + parts = append(parts, fmt.Sprintf("%s (%s)", spec.Type, strings.Join(details, ", "))) } } return strings.Join(parts, ", ") } +// resolvePlacement returns where instanceType will be created ("location" or +// "location/sub-location"). With no requested location it reports the catalog +// default. It errors only when the catalog lists the type's available +// locations and the requested location is not among them; otherwise the +// server stays the source of truth. +func resolvePlacement(catalog []gpusearch.InstanceType, instanceType, location, subLocation string) (string, error) { + var available []string + for _, it := range catalog { + if it.Type != instanceType { + continue + } + if location == "" { + return joinLocation(it.Location, it.SubLocation), nil + } + if slices.Contains(it.AvailableLocations, location) { + return joinLocation(location, subLocation), nil + } + available = append(available, it.AvailableLocations...) + } + if len(available) == 0 { + return joinLocation(location, subLocation), nil + } + slices.Sort(available) + return "", breverrors.NewValidationError(fmt.Sprintf( + "instance type %q is not available in location %q; available locations: %s", + instanceType, location, strings.Join(slices.Compact(available), ", "), + )) +} + +func joinLocation(location, subLocation string) string { + if location == "" || subLocation == "" { + return location + } + return location + "/" + subLocation +} + // createContext holds shared state for instance creation type createContext struct { t *terminal.Terminal @@ -977,6 +1051,14 @@ func newCreateContext(t *terminal.Terminal, store GPUCreateStore, opts GPUCreate return ctx, nil } +// catalog returns the org's instance types, or nil when they could not be fetched. +func (c *createContext) catalog() []gpusearch.InstanceType { + if c.allInstanceTypes == nil { + return nil + } + return c.allInstanceTypes.AllInstanceTypes +} + // typeCreateResult holds the result of creating instances with a single type type typeCreateResult struct { successes []*entity.Workspace @@ -1008,6 +1090,13 @@ func (c *createContext) validateInstanceTypeAvailability(instanceType string) er func (c *createContext) createInstancesWithType(spec InstanceSpec, startIdx, count int) typeCreateResult { result := typeCreateResult{} + location, subLocation := c.opts.requestedPlacement() + if _, err := resolvePlacement(c.catalog(), spec.Type, location, subLocation); err != nil { + c.logf("Skipping: %s\n", err.Error()) + result.hadFailure = true + return result + } + if c.opts.LaunchableID == "" { if err := c.validateInstanceTypeAvailability(spec.Type); err != nil { c.logf("Skipping: %s\n", err.Error()) @@ -1208,7 +1297,7 @@ func RunGPUCreate(parentCtx context.Context, t *terminal.Terminal, gpuCreateStor } ctx.logf("Attempting to create %d instance(s) with %d parallel attempts\n", opts.Count, opts.Parallel) - ctx.logf("Instance types to try: %s\n\n", formatInstanceSpecs(opts.InstanceTypes)) + ctx.logf("Instance types to try: %s\n\n", formatInstanceSpecs(opts.InstanceTypes, ctx.catalog(), opts)) var successfulWorkspaces []*entity.Workspace @@ -1286,6 +1375,8 @@ func (c *createContext) createWorkspace(name string, spec InstanceSpec) (*entity } } + cwOptions.Location, cwOptions.SubLocation = c.opts.requestedPlacement() + if cwOptions.CloudCredID == "" { if c.allInstanceTypes == nil { return nil, breverrors.NewValidationError(fmt.Sprintf( @@ -1397,7 +1488,7 @@ func applyBuildMode(cwOptions *store.CreateWorkspacesOptions, opts GPUCreateOpti } // applyLaunchableConfig populates the workspace create request with all launchable -// configuration, mirroring what the web UI sends when deploying a launchable. +// configuration except placement, which is resolved with explicit flag overrides. func applyLaunchableConfig(cwOptions *store.CreateWorkspacesOptions, launchableID string, info *store.LaunchableResponse, parameterBindings []store.ParameterBinding) { cwOptions.LaunchableConfig = &store.LaunchableConfig{ ID: launchableID, @@ -1419,13 +1510,6 @@ func applyLaunchableWorkspaceRequest(cwOptions *store.CreateWorkspacesOptions, w if cwOptions.CloudCredID == "" && wsReq.CloudCredID != "" { cwOptions.WithCloudCredID(wsReq.CloudCredID) } - // Location / sub-location - if wsReq.Location != "" { - cwOptions.Location = wsReq.Location - } - if wsReq.SubLocation != "" { - cwOptions.SubLocation = wsReq.SubLocation - } if wsReq.ImageID != "" { cwOptions.BaseImage = wsReq.ImageID } diff --git a/pkg/cmd/gpucreate/gpucreate_test.go b/pkg/cmd/gpucreate/gpucreate_test.go index 4fe40eb1..c9b81ea7 100644 --- a/pkg/cmd/gpucreate/gpucreate_test.go +++ b/pkg/cmd/gpucreate/gpucreate_test.go @@ -3,8 +3,11 @@ package gpucreate import ( "context" "encoding/json" + "fmt" + "io" "net/http" "net/http/httptest" + "os" "strings" "testing" "time" @@ -48,6 +51,10 @@ type MockGPUCreateStore struct { CreatedWorkspaces []*entity.Workspace DeletedWorkspaceIDs []string FetchedLifeCycleScriptIDs []string + OrgInstanceTypes []gpusearch.InstanceType // overrides the GetAllInstanceTypesWithCloudCreds default + PublicInstanceTypes []gpusearch.InstanceType // overrides the GetInstanceTypes default + Launchable *store.LaunchableResponse + IncludeCPUCalls []bool // includeCPU argument of each GetInstanceTypes call } func NewMockGPUCreateStore() *MockGPUCreateStore { @@ -119,6 +126,9 @@ func (m *MockGPUCreateStore) GetWorkspaceByNameOrID(orgID string, nameOrID strin } func (m *MockGPUCreateStore) GetAllInstanceTypesWithCloudCreds(orgID string) (*gpusearch.AllInstanceTypesResponse, error) { + if m.OrgInstanceTypes != nil { + return &gpusearch.AllInstanceTypesResponse{AllInstanceTypes: m.OrgInstanceTypes}, nil + } return &gpusearch.AllInstanceTypesResponse{ AllInstanceTypes: []gpusearch.InstanceType{ {Type: "test.fail.quota", CloudCredID: "testkube-brev-test"}, @@ -128,6 +138,9 @@ func (m *MockGPUCreateStore) GetAllInstanceTypesWithCloudCreds(orgID string) (*g } func (m *MockGPUCreateStore) GetLaunchable(launchableID string) (*store.LaunchableResponse, error) { + if m.Launchable != nil { + return m.Launchable, nil + } return &store.LaunchableResponse{ ID: launchableID, Name: "test-launchable", @@ -145,7 +158,11 @@ func (m *MockGPUCreateStore) RedeemCouponCode(organizationID string, code string return &store.RedeemCouponCodeResponse{}, nil } -func (m *MockGPUCreateStore) GetInstanceTypes(_ bool) (*gpusearch.InstanceTypesResponse, error) { +func (m *MockGPUCreateStore) GetInstanceTypes(includeCPU bool) (*gpusearch.InstanceTypesResponse, error) { + m.IncludeCPUCalls = append(m.IncludeCPUCalls, includeCPU) + if m.PublicInstanceTypes != nil { + return &gpusearch.InstanceTypesResponse{Items: m.PublicInstanceTypes}, nil + } // Return a default set of instance types for testing return &gpusearch.InstanceTypesResponse{ Items: []gpusearch.InstanceType{ @@ -161,6 +178,8 @@ func (m *MockGPUCreateStore) GetInstanceTypes(_ bool) (*gpusearch.InstanceTypesR VCPU: 4, BasePrice: gpusearch.BasePrice{Currency: "USD", Amount: "1.006"}, EstimatedDeployTime: "5m0s", + Location: "us-east-1", + AvailableLocations: []string{"us-east-1"}, }, }, }, nil @@ -354,9 +373,6 @@ func TestApplyLaunchableConfig(t *testing.T) { //nolint:funlen // test // Cloud credential from launchable input. assert.Equal(t, "GCP", cwOptions.CloudCredID) - // Location / sub-location - assert.Equal(t, "us-west1", cwOptions.Location) - assert.Equal(t, "us-west1-b", cwOptions.SubLocation) assert.Equal(t, "projects/example/global/images/custom-image", cwOptions.BaseImage) // Storage with Gi suffix assert.Equal(t, "256Gi", cwOptions.DiskStorage) @@ -622,11 +638,11 @@ func TestToHostCIDR(t *testing.T) { // body. Asserting on the marshaled bytes catches typos like "firewall_rules" // or a dropped tag that struct-field assertions can't. func TestLaunchableJSONWireFormat(t *testing.T) { - cwOptions := &store.CreateWorkspacesOptions{} info := &store.LaunchableResponse{ ID: "env-abc", CreateWorkspaceRequest: store.LaunchableWorkspaceRequest{ InstanceType: "n2-standard-4", + CloudCredID: "cc-gcp", Location: "us-west1", SubLocation: "us-west1-b", ImageID: "projects/example/global/images/custom-image", @@ -637,9 +653,18 @@ func TestLaunchableJSONWireFormat(t *testing.T) { }, } - applyLaunchableConfig(cwOptions, "env-abc", info, []store.ParameterBinding{ - {Name: "MODEL", Value: "llama"}, - }) + mock := NewMockGPUCreateStore() + ctx := &createContext{ + store: mock, org: mock.Org, + opts: GPUCreateOptions{ + LaunchableID: "env-abc", LaunchableInfo: info, + ParameterBindings: []store.ParameterBinding{{Name: "MODEL", Value: "llama"}}, + }, + } + _, err := ctx.createWorkspace("wire-test", InstanceSpec{Type: "n2-standard-4"}) + require.NoError(t, err) + require.Len(t, mock.CreatedOptions, 1) + cwOptions := mock.CreatedOptions[0] body, err := json.Marshal(cwOptions) assert.NoError(t, err) @@ -869,7 +894,7 @@ func TestGetFilteredInstanceTypesDefaults(t *testing.T) { // - 500GB disk (>= 500GB requirement) // - A10G GPU = 8.6 capability (>= 8.0 requirement) // - 5m boot time (< 7m requirement) - specs, err := getFilteredInstanceTypes(mock, &searchFilterFlags{}) + specs, _, err := getFilteredInstanceTypes(mock, &searchFilterFlags{}) assert.NoError(t, err) assert.Len(t, specs, 1) assert.Equal(t, "g5.xlarge", specs[0].Type) @@ -880,7 +905,7 @@ func TestGetFilteredInstanceTypesWithGPUName(t *testing.T) { mock := NewMockGPUCreateStore() // Filter by GPU name that matches the mock data - specs, err := getFilteredInstanceTypes(mock, &searchFilterFlags{gpuName: "A10G"}) + specs, _, err := getFilteredInstanceTypes(mock, &searchFilterFlags{gpuName: "A10G"}) assert.NoError(t, err) assert.Len(t, specs, 1) assert.Equal(t, "g5.xlarge", specs[0].Type) @@ -890,7 +915,7 @@ func TestGetFilteredInstanceTypesNoMatch(t *testing.T) { mock := NewMockGPUCreateStore() // Filter by GPU name that doesn't match - specs, err := getFilteredInstanceTypes(mock, &searchFilterFlags{gpuName: "H100"}) + specs, _, err := getFilteredInstanceTypes(mock, &searchFilterFlags{gpuName: "H100"}) assert.NoError(t, err) assert.Len(t, specs, 0) } @@ -989,8 +1014,102 @@ func TestFormatInstanceSpecs(t *testing.T) { {Type: "g6.xlarge", DiskGB: 500}, } - result := formatInstanceSpecs(specs) - assert.Equal(t, "g5.xlarge (1000GB disk), p4d.24xlarge, g6.xlarge (500GB disk)", result) + t.Run("without a catalog or location output is unchanged", func(t *testing.T) { + assert.Equal(t, "g5.xlarge (1000GB disk), p4d.24xlarge, g6.xlarge (500GB disk)", + formatInstanceSpecs(specs, nil, GPUCreateOptions{})) + }) + + catalog := locationCatalog() + cpu := []InstanceSpec{{Type: "n2d-standard-2", DiskGB: 120}, {Type: "m5.large"}} + + t.Run("shows the catalog default location", func(t *testing.T) { + assert.Equal(t, "n2d-standard-2 (120GB disk, location: asia-south1/asia-south1-a), m5.large (location: us-east-1)", + formatInstanceSpecs(cpu, catalog, GPUCreateOptions{})) + }) + + t.Run("shows the requested location, or that a type is not available there", func(t *testing.T) { + assert.Equal(t, "n2d-standard-2 (120GB disk, location: us-west2/us-west2-a), m5.large (not available in us-west2)", + formatInstanceSpecs(cpu, catalog, GPUCreateOptions{Location: "us-west2", SubLocation: "us-west2-a"})) + }) +} + +// locationCatalog mirrors the live catalog shape from issue #454: n2d-standard-2 +// defaults to asia-south1 but is also available in us-west2. +func locationCatalog() []gpusearch.InstanceType { + return []gpusearch.InstanceType{ + { + Type: "n2d-standard-2", + CloudCredID: "cc-gcp", + Location: "asia-south1", + SubLocation: "asia-south1-a", + AvailableLocations: []string{"asia-south1", "us-west2", "us-west3"}, + }, + { + Type: "m5.large", + CloudCredID: "cc-aws", + Location: "us-east-1", + AvailableLocations: []string{"us-east-1", "us-east-2"}, + }, + {Type: "no-locations", CloudCredID: "cc-x"}, + } +} + +func TestResolvePlacement(t *testing.T) { + catalog := locationCatalog() + cases := []struct { + name, instanceType, location, subLocation string + catalog []gpusearch.InstanceType + want string + wantErr string + }{ + {name: "default location and sub-location", instanceType: "n2d-standard-2", want: "asia-south1/asia-south1-a"}, + {name: "default location without sub-location", instanceType: "m5.large", want: "us-east-1"}, + {name: "requested location", instanceType: "n2d-standard-2", location: "us-west2", want: "us-west2"}, + {name: "requested location and sub-location", instanceType: "n2d-standard-2", location: "us-west2", subLocation: "us-west2-a", want: "us-west2/us-west2-a"}, + { + name: "unavailable location lists sorted alternatives", instanceType: "n2d-standard-2", location: "us-east-1", + wantErr: `instance type "n2d-standard-2" is not available in location "us-east-1"; available locations: asia-south1, us-west2, us-west3`, + }, + {name: "match is exact", instanceType: "n2d-standard-2", location: "US-WEST2", wantErr: "not available"}, + {name: "type absent from the catalog is left to the server", instanceType: "private-type", location: "us-west2", want: "us-west2"}, + {name: "type absent from the catalog has no default", instanceType: "private-type", want: ""}, + {name: "type without listed locations is left to the server", instanceType: "no-locations", location: "us-west2", want: "us-west2"}, + {name: "no catalog", instanceType: "n2d-standard-2", location: "us-west2", catalog: []gpusearch.InstanceType{}, want: "us-west2"}, + { + name: "any catalog row for the type may offer the location", instanceType: "dup", location: "b", + catalog: []gpusearch.InstanceType{ + {Type: "dup", AvailableLocations: []string{"a"}}, + {Type: "dup", AvailableLocations: []string{"b"}}, + }, + want: "b", + }, + { + name: "alternatives from duplicate rows are de-duplicated", instanceType: "dup", location: "z", + catalog: []gpusearch.InstanceType{ + {Type: "dup", AvailableLocations: []string{"b", "a"}}, + {Type: "dup", AvailableLocations: []string{"a"}}, + }, + wantErr: "available locations: a, b", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := catalog + if tc.catalog != nil { + c = tc.catalog + } + got, err := resolvePlacement(c, tc.instanceType, tc.location, tc.subLocation) + if tc.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + var ve breverrors.ValidationError + assert.ErrorAs(t, err, &ve) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } } // TestPollUntilReady covers the readiness-wait behavior across ctx states and @@ -1446,3 +1565,295 @@ func TestCreateInstancesWithType(t *testing.T) { }) } } + +// TestCreateWorkspaceLocation covers what reaches the create request. +func TestCreateWorkspaceLocation(t *testing.T) { //nolint:funlen // table-driven test + launchable := &store.LaunchableResponse{ + ID: "env-abc", Name: "test-launchable", + CreateWorkspaceRequest: store.LaunchableWorkspaceRequest{ + CloudCredID: "cc-from-launchable", InstanceType: "private-type", + Location: "europe-west4", SubLocation: "europe-west4-a", + }, + } + cases := []struct { + name string + spec string + opts GPUCreateOptions + wantCreated bool + wantLocation string + wantSubLocation string + }{ + { + name: "no location leaves placement to the server", + spec: "n2d-standard-2", + wantCreated: true, + }, + { + name: "issue #454: n2d-standard-2 in us-west2/us-west2-a", + spec: "n2d-standard-2", + opts: GPUCreateOptions{Location: "us-west2", SubLocation: "us-west2-a"}, + wantCreated: true, + wantLocation: "us-west2", wantSubLocation: "us-west2-a", + }, + { + name: "location without sub-location", + spec: "n2d-standard-2", + opts: GPUCreateOptions{Location: "us-west2"}, + wantCreated: true, + wantLocation: "us-west2", + }, + { + name: "unavailable location skips the type without creating", + spec: "n2d-standard-2", + opts: GPUCreateOptions{Location: "us-east-1"}, + }, + { + name: "launchable keeps its own placement", + spec: "private-type", + opts: GPUCreateOptions{LaunchableID: "env-abc", LaunchableInfo: launchable}, + wantCreated: true, + wantLocation: "europe-west4", wantSubLocation: "europe-west4-a", + }, + { + name: "--location replaces launchable placement and drops its sub-location", + spec: "private-type", + opts: GPUCreateOptions{LaunchableID: "env-abc", LaunchableInfo: launchable, Location: "us-west2"}, + wantCreated: true, + wantLocation: "us-west2", + }, + { + name: "--location and --sub-location replace launchable placement", + spec: "private-type", + opts: GPUCreateOptions{LaunchableID: "env-abc", LaunchableInfo: launchable, Location: "us-west2", SubLocation: "us-west2-b"}, + wantCreated: true, + wantLocation: "us-west2", wantSubLocation: "us-west2-b", + }, + { + name: "launchable with a catalog type is validated too", + spec: "n2d-standard-2", + opts: GPUCreateOptions{LaunchableID: "env-abc", LaunchableInfo: launchable, Location: "us-east-1"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockGPUCreateStore() + opts := tc.opts + opts.Count, opts.Parallel, opts.Name = 1, 1, "loc-test" + var logs strings.Builder + ctx := &createContext{ + t: terminal.New(), store: mock, opts: opts, org: mock.Org, piped: true, + allInstanceTypes: &gpusearch.AllInstanceTypesResponse{AllInstanceTypes: locationCatalog()}, + logf: func(format string, a ...interface{}) { fmt.Fprintf(&logs, format, a...) }, + } + + result := ctx.createInstancesWithType(InstanceSpec{Type: tc.spec}, 0, 1) + + if !tc.wantCreated { + assert.True(t, result.hadFailure) + assert.NoError(t, result.fatalError, "a type unavailable in the location should fall through to the next type") + assert.Empty(t, mock.CreatedOptions) + assert.Contains(t, logs.String(), "available locations: asia-south1, us-west2, us-west3") + return + } + require.Len(t, mock.CreatedOptions, 1) + assert.Equal(t, tc.wantLocation, mock.CreatedOptions[0].Location) + assert.Equal(t, tc.wantSubLocation, mock.CreatedOptions[0].SubLocation) + + body, err := json.Marshal(mock.CreatedOptions[0]) + require.NoError(t, err) + if tc.wantLocation == "" { + assert.NotContains(t, string(body), `"location"`, "omitted so the server picks the default") + } else { + assert.Contains(t, string(body), `"location":"`+tc.wantLocation+`"`) + } + if tc.wantSubLocation == "" { + assert.NotContains(t, string(body), `"subLocation"`) + } else { + assert.Contains(t, string(body), `"subLocation":"`+tc.wantSubLocation+`"`) + } + }) + } +} + +// captureStdout returns what fn writes to os.Stdout. Build terminals inside fn: +// terminal.New binds os.Stdout when it is created. +func captureStdout(t *testing.T, fn func()) string { + t.Helper() + r, w, err := os.Pipe() + require.NoError(t, err) + orig := os.Stdout + os.Stdout = w + defer func() { os.Stdout = orig }() + fn() + require.NoError(t, w.Close()) + out, err := io.ReadAll(r) + require.NoError(t, err) + return string(out) +} + +// TestCreateCommandLocation drives the cobra command end to end with a mock store. +func TestCreateCommandLocation(t *testing.T) { + run := func(mock *MockGPUCreateStore, args ...string) (string, error) { + var err error + out := captureStdout(t, func() { + cmd := NewCmdGPUCreate(terminal.New(), mock) + cmd.SetArgs(args) + err = cmd.Execute() + }) + return out, err //nolint:wrapcheck // test helper returns the command error as-is + } + newMock := func() *MockGPUCreateStore { + mock := NewMockGPUCreateStore() + mock.OrgInstanceTypes = locationCatalog() + mock.PublicInstanceTypes = locationCatalog() + return mock + } + + t.Run("--sub-location requires --location", func(t *testing.T) { + mock := newMock() + _, err := run(mock, "mybox", "--type", "n2d-standard-2", "--sub-location", "us-west2-a", "--detached") + require.Error(t, err) + assert.Contains(t, err.Error(), "--sub-location requires --location") + assert.Empty(t, mock.CreatedOptions) + }) + + t.Run("issue #454 repro creates in the requested location", func(t *testing.T) { + mock := newMock() + _, err := run(mock, "mybox", "--type", "n2d-standard-2", "--location", "us-west2", "--sub-location", "us-west2-a", "--detached") + require.NoError(t, err) + require.Len(t, mock.CreatedOptions, 1) + assert.Equal(t, "n2d-standard-2", mock.CreatedOptions[0].InstanceType) + assert.Equal(t, "us-west2", mock.CreatedOptions[0].Location) + assert.Equal(t, "us-west2-a", mock.CreatedOptions[0].SubLocation) + assert.Equal(t, "cc-gcp", mock.CreatedOptions[0].CloudCredID) + }) + + t.Run("unavailable location fails without creating", func(t *testing.T) { + mock := newMock() + _, err := run(mock, "mybox", "--type", "n2d-standard-2", "--location", "us-east-1", "--detached") + require.Error(t, err) + assert.Contains(t, err.Error(), "could only create 0/1") + assert.Empty(t, mock.CreatedOptions) + }) + + t.Run("fallback chain skips types unavailable in the location", func(t *testing.T) { + mock := newMock() + _, err := run(mock, "mybox", "--type", "m5.large,n2d-standard-2", "--location", "us-west2", "--detached") + require.NoError(t, err) + require.Len(t, mock.CreatedOptions, 1) + assert.Equal(t, "n2d-standard-2", mock.CreatedOptions[0].InstanceType) + assert.Equal(t, "us-west2", mock.CreatedOptions[0].Location) + }) + + t.Run("dry run shows the default location without creating", func(t *testing.T) { + mock := newMock() + out, err := run(mock, "mybox", "--type", "n2d-standard-2", "--dry-run") + require.NoError(t, err) + assert.Equal(t, "n2d-standard-2 (location: asia-south1/asia-south1-a)\n", out) + assert.Empty(t, mock.CreatedOptions) + }) + + t.Run("dry run shows the requested location", func(t *testing.T) { + mock := newMock() + out, err := run(mock, "mybox", "--type", "n2d-standard-2,m5.large", "--location", "us-west2", "--sub-location", "us-west2-a", "--dry-run") + require.NoError(t, err) + assert.Equal(t, "n2d-standard-2 (location: us-west2/us-west2-a), m5.large (not available in us-west2)\n", out) + assert.Empty(t, mock.CreatedOptions) + }) + + t.Run("auto-selection only considers types available in the location", func(t *testing.T) { + mock := NewMockGPUCreateStore() // default GPU catalog: g5.xlarge in us-east-1 only + out, err := run(mock, "mybox", "--location", "us-east-1", "--dry-run") + require.NoError(t, err) + assert.Contains(t, out, "g5.xlarge") + assert.Contains(t, out, "us-east-1") + assert.Equal(t, []bool{true}, mock.IncludeCPUCalls, "dry-run reuses the catalog fetched for auto-selection") + + _, err = run(mock, "mybox", "--location", "us-west2", "--dry-run") + require.Error(t, err) + assert.Contains(t, err.Error(), "no GPU instances match") + }) +} + +// TestSearchOutputPipesIntoCreate checks that 'brev search | brev create --stdin' +// still parses the type and target disk now that search prints locations. +func TestSearchOutputPipesIntoCreate(t *testing.T) { + instances := gpusearch.ProcessInstances([]gpusearch.InstanceType{{ + Type: "n2d-standard-2", Provider: "gcp", VCPU: 2, Memory: "8GiB", + SupportedStorage: []gpusearch.Storage{{MinSize: "10GiB", MaxSize: "16TiB"}}, + Location: "asia-south1", + SubLocation: "asia-south1-a", + AvailableLocations: []string{"asia-south1", "us-west2"}, + }}) + instances[0].TargetDisk = 120 + + table := captureStdout(t, func() { + require.NoError(t, gpusearch.DisplayCPUResults(terminal.New(), instances, false, true)) + }) + assert.Equal(t, []InstanceSpec{{Type: "n2d-standard-2", DiskGB: 120}}, parseTableInput(table)) + + jsonOut := captureStdout(t, func() { + require.NoError(t, gpusearch.DisplayCPUResults(terminal.New(), instances, true, true)) + }) + assert.Contains(t, jsonOut, `"available_locations"`) + specs, err := parseJSONInput(jsonOut) + require.NoError(t, err) + assert.Equal(t, []InstanceSpec{{Type: "n2d-standard-2", DiskGB: 120}}, specs) +} + +// The preview and pre-create log must describe the placement sent to the API, +// including a launchable's saved placement when no override was supplied. +func TestLaunchablePlacementPreviewMatchesCreate(t *testing.T) { + for _, tc := range []struct { + name, instanceType, location, subLocation, wantPlacement string + }{ + {"saved placement", "n2d-standard-2", "", "", "us-west2/us-west2-a"}, + {"private launchable type", "private-type", "", "", "us-west2/us-west2-a"}, + {"override clears saved zone", "n2d-standard-2", "us-west3", "", "us-west3"}, + {"override includes zone", "n2d-standard-2", "us-west3", "us-west3-b", "us-west3/us-west3-b"}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, dryRun := range []bool{true, false} { + t.Run(fmt.Sprintf("dry-run=%t", dryRun), func(t *testing.T) { + mock := NewMockGPUCreateStore() + mock.PublicInstanceTypes, mock.OrgInstanceTypes = locationCatalog(), locationCatalog() + mock.Launchable = &store.LaunchableResponse{ + ID: "env-abc", Name: "saved-placement", + CreateWorkspaceRequest: store.LaunchableWorkspaceRequest{ + InstanceType: tc.instanceType, CloudCredID: "cc-gcp", + Location: "us-west2", SubLocation: "us-west2-a", + }, + } + args := []string{"mybox", "--launchable", "env-abc", "--detached"} + if dryRun { + args = append(args, "--dry-run") + } + if tc.location != "" { + args = append(args, "--location", tc.location) + } + if tc.subLocation != "" { + args = append(args, "--sub-location", tc.subLocation) + } + out := captureStdout(t, func() { + // Creation logs go to stderr when stdout is piped. + originalStderr := os.Stderr + os.Stderr = os.Stdout + defer func() { os.Stderr = originalStderr }() + cmd := NewCmdGPUCreate(terminal.New(), mock) + cmd.SetArgs(args) + require.NoError(t, cmd.Execute()) + }) + assert.Contains(t, out, tc.instanceType+" (location: "+tc.wantPlacement+")") + if dryRun { + assert.Empty(t, mock.CreatedOptions) + return + } + require.Len(t, mock.CreatedOptions, 1) + location, zone, _ := strings.Cut(tc.wantPlacement, "/") + assert.Equal(t, location, mock.CreatedOptions[0].Location) + assert.Equal(t, zone, mock.CreatedOptions[0].SubLocation) + }) + } + }) + } +} diff --git a/pkg/cmd/gpusearch/gpusearch.go b/pkg/cmd/gpusearch/gpusearch.go index d9060da9..250e4b66 100644 --- a/pkg/cmd/gpusearch/gpusearch.go +++ b/pkg/cmd/gpusearch/gpusearch.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "regexp" + "slices" "sort" "strconv" "strings" @@ -121,13 +122,18 @@ type GPUSearchStore interface { var ( searchLong = `Search instance types available on Brev. -The search command has two subcommands: - gpu Search GPU instance types (default when no subcommand is given) - cpu Search CPU-only instance types +The search command has three subcommands: + gpu Search GPU instance types (default when no subcommand is given) + cpu Search CPU-only instance types + locations List locations that instance types can be created in Use 'brev search' or 'brev search gpu' to find GPU instances. Use 'brev search cpu' to find CPU-only instances. +The LOCATION column shows where each type is created by default. Use +'brev search locations' to list locations, and --location to list only the types +available in one ('brev create --location' accepts the same values). + Features column shows instance capabilities: S = Stoppable (can stop and restart without losing data) R = Rebootable (can reboot the instance) @@ -144,6 +150,9 @@ Features column shows instance capabilities: # Filter by minimum VRAM per GPU (in GB) brev search gpu --min-vram 24 + # Only types available in a location (exact match) + brev search gpu --location us-east-1 + # Wide output (includes RAM, ARCH columns) brev search gpu --wide @@ -159,6 +168,9 @@ Features column shows instance capabilities: # Filter by provider brev search cpu --provider aws + # Only types available in a location (exact match) + brev search cpu --location us-west2 + # Filter by minimum RAM brev search cpu --min-ram 64 @@ -172,6 +184,7 @@ Features column shows instance capabilities: // sharedFlags holds flags shared between gpu and cpu subcommands type sharedFlags struct { + location string provider string arch string minVCPU int @@ -188,6 +201,7 @@ type sharedFlags struct { // addSharedFlags adds common flags to a command func addSharedFlags(cmd *cobra.Command, f *sharedFlags) { + cmd.Flags().StringVar(&f.location, "location", "", "Only show types available in this location (exact match, e.g., us-west2)") cmd.Flags().StringVarP(&f.provider, "provider", "p", "", "Filter by provider/cloud (case-insensitive, partial match)") cmd.Flags().StringVar(&f.arch, "arch", "", "Filter by architecture (e.g., x86_64, arm64)") cmd.Flags().IntVar(&f.minVCPU, "min-vcpu", 0, "Minimum number of vCPUs") @@ -220,7 +234,7 @@ func NewCmdGPUSearch(t *terminal.Terminal, store GPUSearchStore) *cobra.Command Short: "Search GPU and CPU instance types", Long: searchLong, Example: gpuExample, - ValidArgs: []string{"cpu", "gpu"}, + ValidArgs: []string{"cpu", "gpu", "locations"}, Args: func(cmd *cobra.Command, args []string) error { // The parent runs GPU search by default when no positional args are // given. Unknown positional tokens (e.g. "cpus", "CPU", "badcmd") @@ -233,7 +247,7 @@ func NewCmdGPUSearch(t *terminal.Terminal, store GPUSearchStore) *cobra.Command path := cmd.CommandPath() return breverrors.NewValidationError(fmt.Sprintf( "unknown subcommand %q for %q.\n"+ - "Available subcommands: cpu, gpu.\n"+ + "Available subcommands: cpu, gpu, locations.\n"+ "Use %q (default) or %q gpu for GPU instances; use %q cpu for CPU-only instances.\n"+ "Run %q --help for more details.", args[0], path, path, path, path, path, @@ -241,7 +255,7 @@ func NewCmdGPUSearch(t *terminal.Terminal, store GPUSearchStore) *cobra.Command }, RunE: func(cmd *cobra.Command, args []string) error { // Default behavior: GPU search - return RunGPUSearch(t, store, gpuName, shared.provider, shared.arch, minVRAM, minTotalVRAM, minCapability, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput, wide) + return RunGPUSearch(t, store, gpuName, shared.location, shared.provider, shared.arch, minVRAM, minTotalVRAM, minCapability, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput, wide) }, } @@ -256,6 +270,7 @@ func NewCmdGPUSearch(t *terminal.Terminal, store GPUSearchStore) *cobra.Command // Add subcommands cmd.AddCommand(newCmdGPUSubcommand(t, store)) cmd.AddCommand(newCmdCPUSubcommand(t, store)) + cmd.AddCommand(newCmdLocationsSubcommand(t, store)) return cmd } @@ -275,7 +290,7 @@ func newCmdGPUSubcommand(t *terminal.Terminal, store GPUSearchStore) *cobra.Comm Short: "Search GPU instance types", Example: gpuExample, RunE: func(cmd *cobra.Command, args []string) error { - return RunGPUSearch(t, store, gpuName, shared.provider, shared.arch, minVRAM, minTotalVRAM, minCapability, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput, wide) + return RunGPUSearch(t, store, gpuName, shared.location, shared.provider, shared.arch, minVRAM, minTotalVRAM, minCapability, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput, wide) }, } @@ -299,7 +314,7 @@ func newCmdCPUSubcommand(t *terminal.Terminal, store GPUSearchStore) *cobra.Comm Short: "Search CPU-only instance types", Example: cpuExample, RunE: func(cmd *cobra.Command, args []string) error { - return RunCPUSearch(t, store, shared.provider, shared.arch, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput) + return RunCPUSearch(t, store, shared.location, shared.provider, shared.arch, shared.minRAM, shared.minDisk, shared.minVCPU, shared.maxBootTime, shared.stoppable, shared.rebootable, shared.flexPorts, shared.sortBy, shared.descending, shared.jsonOutput) }, } @@ -332,6 +347,12 @@ type GPUInstanceInfo struct { TargetDisk float64 `json:"target_disk_gb,omitempty"` PricePerHour float64 `json:"price_per_hour"` Manufacturer string `json:"-"` // exclude from JSON output + + // Location is where the type is created: the catalog default, or the + // --location value when filtering by location. + Location string `json:"location,omitempty"` + SubLocation string `json:"sub_location,omitempty"` + AvailableLocations []string `json:"available_locations,omitempty"` } // IsStdoutPiped returns true if stdout is being piped (not a terminal) @@ -341,14 +362,17 @@ func IsStdoutPiped() bool { } // RunGPUSearch executes the GPU search with filters and sorting -func RunGPUSearch(t *terminal.Terminal, store GPUSearchStore, gpuName, provider, arch string, minVRAM, minTotalVRAM, minCapability, minRAM, minDisk float64, minVCPU, maxBootTime int, stoppable, rebootable, flexPorts bool, sortBy string, descending, jsonOutput, wide bool) error { +func RunGPUSearch(t *terminal.Terminal, store GPUSearchStore, gpuName, location, provider, arch string, minVRAM, minTotalVRAM, minCapability, minRAM, minDisk float64, minVCPU, maxBootTime int, stoppable, rebootable, flexPorts bool, sortBy string, descending, jsonOutput, wide bool) error { if err := validateSortOption(sortBy); err != nil { return err } piped := IsStdoutPiped() - response, err := store.GetInstanceTypes(false) + // The CPU-inclusive catalog matches what 'brev create' uses (default + // location, price, available locations); the GPU-only listing can return a + // different region variant of a type. GPU types are filtered below. + response, err := store.GetInstanceTypes(true) if err != nil { return breverrors.WrapAndTrace(err) } @@ -360,7 +384,8 @@ func RunGPUSearch(t *terminal.Terminal, store GPUSearchStore, gpuName, provider, instances := ProcessInstances(response.Items) // Filter to GPU-only instances - filtered := FilterInstances(instances, gpuName, provider, arch, minVRAM, minTotalVRAM, minCapability, minRAM, minDisk, minVCPU, maxBootTime, stoppable, rebootable, flexPorts, false) + filtered := FilterInstances(instances, gpuName, provider, arch, minVRAM, minTotalVRAM, minCapability, minRAM, minDisk, minVCPU, maxBootTime, stoppable, rebootable, flexPorts, true) + filtered = FilterByLocation(filtered, location) if len(filtered) == 0 { return displayEmptyResults(t, "No GPU instances match the specified filters", jsonOutput, piped) @@ -372,7 +397,7 @@ func RunGPUSearch(t *terminal.Terminal, store GPUSearchStore, gpuName, provider, } // RunCPUSearch executes the CPU search with filters and sorting -func RunCPUSearch(t *terminal.Terminal, store GPUSearchStore, provider, arch string, minRAM, minDisk float64, minVCPU, maxBootTime int, stoppable, rebootable, flexPorts bool, sortBy string, descending, jsonOutput bool) error { +func RunCPUSearch(t *terminal.Terminal, store GPUSearchStore, location, provider, arch string, minRAM, minDisk float64, minVCPU, maxBootTime int, stoppable, rebootable, flexPorts bool, sortBy string, descending, jsonOutput bool) error { if err := validateSortOption(sortBy); err != nil { return err } @@ -392,6 +417,7 @@ func RunCPUSearch(t *terminal.Terminal, store GPUSearchStore, provider, arch str // Filter to CPU-only instances filtered := FilterCPUInstances(instances, provider, arch, minRAM, minDisk, minVCPU, maxBootTime, stoppable, rebootable, flexPorts) + filtered = FilterByLocation(filtered, location) if len(filtered) == 0 { return displayEmptyResults(t, "No CPU instances match the specified filters", jsonOutput, piped) @@ -787,6 +813,10 @@ func ProcessInstances(items []InstanceType) []GPUInstanceInfo { FlexPorts: item.CanModifyFirewallRules, PricePerHour: price, Manufacturer: "cpu", + + Location: item.Location, + SubLocation: item.SubLocation, + AvailableLocations: item.AvailableLocations, }) continue } @@ -823,6 +853,10 @@ func ProcessInstances(items []InstanceType) []GPUInstanceInfo { FlexPorts: item.CanModifyFirewallRules, PricePerHour: price, Manufacturer: gpu.Manufacturer, + + Location: item.Location, + SubLocation: item.SubLocation, + AvailableLocations: item.AvailableLocations, }) } } @@ -958,6 +992,23 @@ func FilterCPUInstances(instances []GPUInstanceInfo, provider, arch string, minR return FilterInstances(cpuOnly, "", provider, arch, 0, 0, 0, minRAM, minDisk, minVCPU, maxBootTime, stoppable, rebootable, flexPorts, false) } +// FilterByLocation keeps instances available in location (exact match) and +// reports that location as where they will be created. An empty location is a no-op. +func FilterByLocation(instances []GPUInstanceInfo, location string) []GPUInstanceInfo { + if location == "" { + return instances + } + var filtered []GPUInstanceInfo + for _, inst := range instances { + if slices.Contains(inst.AvailableLocations, location) { + inst.Location = location + inst.SubLocation = "" + filtered = append(filtered, inst) + } + } + return filtered +} + // SortInstances sorts the instance list by the specified column // //nolint:gocyclo @@ -1083,6 +1134,7 @@ type formattedInstanceFields struct { Features string Price string Provider string + Location string TargetDisk string } @@ -1113,6 +1165,11 @@ func formatInstanceFields(inst GPUInstanceInfo, includeUnits bool) formattedInst providerStr = fmt.Sprintf("%s:%s", inst.Cloud, inst.Provider) } + locationStr := inst.Location + if locationStr == "" { + locationStr = "-" + } + var ramStr string if includeUnits { ramStr = fmt.Sprintf("%.0f GB", inst.RAMInGB) @@ -1131,6 +1188,7 @@ func formatInstanceFields(inst GPUInstanceInfo, includeUnits bool) formattedInst Features: formatFeatures(inst.Stoppable, inst.Rebootable, inst.FlexPorts), Price: fmt.Sprintf("$%.2f", inst.PricePerHour), Provider: providerStr, + Location: locationStr, TargetDisk: fmt.Sprintf("%.0f", inst.TargetDisk), } } @@ -1141,7 +1199,7 @@ func displayGPUTable(t *terminal.Terminal, instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "PROVIDER", "GPU", "COUNT", "VRAM/GPU", "TOTAL VRAM", "CAPABILITY", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} + header := table.Row{"TYPE", "PROVIDER", "LOCATION", "GPU", "COUNT", "VRAM/GPU", "TOTAL VRAM", "CAPABILITY", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1149,6 +1207,7 @@ func displayGPUTable(t *terminal.Terminal, instances []GPUInstanceInfo) { row := table.Row{ inst.Type, f.Provider, + f.Location, t.Green(inst.GPUName), inst.GPUCount, f.VRAM, @@ -1175,7 +1234,7 @@ func displayGPUTablePlain(instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "GPU", "COUNT", "VRAM/GPU", "TOTAL_VRAM", "CAPABILITY", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} + header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "LOCATION", "GPU", "COUNT", "VRAM/GPU", "TOTAL_VRAM", "CAPABILITY", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1184,6 +1243,7 @@ func displayGPUTablePlain(instances []GPUInstanceInfo) { inst.Type, f.TargetDisk, f.Provider, + f.Location, inst.GPUName, inst.GPUCount, f.VRAM, @@ -1208,7 +1268,7 @@ func displayGPUTableWide(t *terminal.Terminal, instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "PROVIDER", "GPU", "COUNT", "VRAM/GPU", "TOTAL VRAM", "CAPABILITY", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} + header := table.Row{"TYPE", "PROVIDER", "LOCATION", "GPU", "COUNT", "VRAM/GPU", "TOTAL VRAM", "CAPABILITY", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1216,6 +1276,7 @@ func displayGPUTableWide(t *terminal.Terminal, instances []GPUInstanceInfo) { row := table.Row{ inst.Type, f.Provider, + f.Location, t.Green(inst.GPUName), inst.GPUCount, f.VRAM, @@ -1242,7 +1303,7 @@ func displayGPUTablePlainWide(instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "GPU", "COUNT", "VRAM/GPU", "TOTAL_VRAM", "CAPABILITY", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} + header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "LOCATION", "GPU", "COUNT", "VRAM/GPU", "TOTAL_VRAM", "CAPABILITY", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "VCPUs", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1251,6 +1312,7 @@ func displayGPUTablePlainWide(instances []GPUInstanceInfo) { inst.Type, f.TargetDisk, f.Provider, + f.Location, inst.GPUName, inst.GPUCount, f.VRAM, @@ -1277,7 +1339,7 @@ func displayCPUTable(instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "PROVIDER", "VCPUs", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "$/HR"} + header := table.Row{"TYPE", "PROVIDER", "LOCATION", "VCPUs", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1285,6 +1347,7 @@ func displayCPUTable(instances []GPUInstanceInfo) { row := table.Row{ inst.Type, f.Provider, + f.Location, inst.VCPUs, f.RAM, inst.Arch, @@ -1306,7 +1369,7 @@ func displayCPUTablePlain(instances []GPUInstanceInfo) { ta.SetOutputMirror(os.Stdout) ta.Style().Options = getBrevTableOptions() - header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "VCPUs", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "$/HR"} + header := table.Row{"TYPE", "TARGET_DISK", "PROVIDER", "LOCATION", "VCPUs", "RAM", "ARCH", "DISK", "$/GB/MO", "BOOT", "FEATURES", "$/HR"} ta.AppendHeader(header) for _, inst := range instances { @@ -1315,6 +1378,7 @@ func displayCPUTablePlain(instances []GPUInstanceInfo) { inst.Type, f.TargetDisk, f.Provider, + f.Location, inst.VCPUs, f.RAM, inst.Arch, diff --git a/pkg/cmd/gpusearch/gpusearch_test.go b/pkg/cmd/gpusearch/gpusearch_test.go index 5749d3a6..4b634b4a 100644 --- a/pkg/cmd/gpusearch/gpusearch_test.go +++ b/pkg/cmd/gpusearch/gpusearch_test.go @@ -1,10 +1,16 @@ package gpusearch import ( + "encoding/json" + "fmt" + "io" + "os" + "strings" "testing" "github.com/brevdev/brev-cli/pkg/terminal" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // MockGPUSearchStore is a mock implementation of GPUSearchStore for testing @@ -648,37 +654,40 @@ func (m *trackingStore) GetInstanceTypes(includeCPU bool) (*InstanceTypesRespons return &InstanceTypesResponse{Items: []InstanceType{}}, nil } -func TestSearchCommandDefaultsToGPUSearchWhenNoArgs(t *testing.T) { - store := &trackingStore{} +// searchTypes runs the search command with --json and returns the listed types. +func searchTypes(t *testing.T, args ...string) ([]string, *trackingStore) { + t.Helper() + store := &trackingStore{Response: locationCatalog()} cmd := NewCmdGPUSearch(terminal.New(), store) - cmd.SetArgs([]string{}) - - err := cmd.Execute() - assert.NoError(t, err) - assert.Len(t, store.calls, 1, "default search should call the store once") - assert.False(t, store.calls[0], "default search should request GPU instances (includeCPU=false)") -} - -func TestSearchCommandGPUSubcommandDispatchesToGPUSearch(t *testing.T) { - store := &trackingStore{} - cmd := NewCmdGPUSearch(terminal.New(), store) - cmd.SetArgs([]string{"gpu"}) - - err := cmd.Execute() - assert.NoError(t, err) - assert.Len(t, store.calls, 1, "gpu subcommand should call the store once") - assert.False(t, store.calls[0], "gpu subcommand should request GPU instances (includeCPU=false)") + cmd.SetArgs(append(args, "--json")) + out := captureStdout(t, func() { require.NoError(t, cmd.Execute()) }) + var found []GPUInstanceInfo + require.NoError(t, json.Unmarshal([]byte(out), &found)) + var types []string + for _, inst := range found { + types = append(types, inst.Type) + } + return types, store } -func TestSearchCommandCPUSubcommandDispatchesToCPUSearch(t *testing.T) { - store := &trackingStore{} - cmd := NewCmdGPUSearch(terminal.New(), store) - cmd.SetArgs([]string{"cpu"}) - - err := cmd.Execute() - assert.NoError(t, err) - assert.Len(t, store.calls, 1, "cpu subcommand should call the store once") - assert.True(t, store.calls[0], "cpu subcommand should request CPU instances (includeCPU=true)") +func TestSearchCommandDispatch(t *testing.T) { + cpuTypes := []string{"cpu-no-location", "n2d-standard-2", "m5.large"} // sorted by price + for _, tc := range []struct { + name string + args []string + want []string + }{ + {"default search lists GPU types", nil, []string{"g5.xlarge"}}, + {"gpu subcommand lists GPU types", []string{"gpu"}, []string{"g5.xlarge"}}, + {"cpu subcommand lists CPU types", []string{"cpu"}, cpuTypes}, + } { + t.Run(tc.name, func(t *testing.T) { + types, store := searchTypes(t, tc.args...) + assert.Equal(t, tc.want, types) + // One catalog for every command, the same one 'brev create' validates against. + assert.Equal(t, []bool{true}, store.calls) + }) + } } func TestSearchCommandRejectsUnknownPositionalTokens(t *testing.T) { @@ -700,8 +709,200 @@ func TestSearchCommandRejectsUnknownPositionalTokens(t *testing.T) { err := cmd.Execute() assert.Error(t, err) assert.ErrorContains(t, err, "unknown subcommand") - assert.ErrorContains(t, err, "Available subcommands: cpu, gpu") + assert.ErrorContains(t, err, "Available subcommands: cpu, gpu, locations") assert.Empty(t, store.calls, "unknown subcommand should not call the store") }) } } + +// captureStdout returns what fn writes to os.Stdout. Tables and JSON are +// written there directly, and a pipe makes IsStdoutPiped report true. +func captureStdout(t *testing.T, fn func()) string { + t.Helper() + r, w, err := os.Pipe() + require.NoError(t, err) + orig := os.Stdout + os.Stdout = w + defer func() { os.Stdout = orig }() + fn() + require.NoError(t, w.Close()) + out, err := io.ReadAll(r) + require.NoError(t, err) + return string(out) +} + +// locationCatalog mirrors the live catalog shape from issue #454: n2d-standard-2 +// defaults to asia-south1 but is also available in us-west2. +func locationCatalog() *InstanceTypesResponse { + return &InstanceTypesResponse{Items: []InstanceType{ + { + Type: "n2d-standard-2", Provider: "gcp", VCPU: 2, Memory: "8GiB", + BasePrice: BasePrice{Currency: "USD", Amount: "0.07"}, + Location: "asia-south1", + SubLocation: "asia-south1-a", + AvailableLocations: []string{"asia-south1", "us-west2"}, + }, + { + Type: "m5.large", Provider: "aws", VCPU: 2, Memory: "8GiB", + BasePrice: BasePrice{Currency: "USD", Amount: "0.10"}, + Location: "us-east-1", + AvailableLocations: []string{"us-east-1"}, + }, + { + Type: "g5.xlarge", Provider: "aws", VCPU: 4, Memory: "16GiB", + SupportedGPUs: []GPU{{Count: 1, Name: "A10G", Manufacturer: "NVIDIA", Memory: "24GiB"}}, + BasePrice: BasePrice{Currency: "USD", Amount: "1.006"}, + Location: "us-east-1", + AvailableLocations: []string{"us-east-1", "us-west-2"}, + }, + {Type: "cpu-no-location", Provider: "aws", VCPU: 2, Memory: "8GiB"}, + }} +} + +func TestProcessInstancesCopiesLocations(t *testing.T) { + byType := map[string]GPUInstanceInfo{} + for _, inst := range ProcessInstances(locationCatalog().Items) { + byType[inst.Type] = inst + } + + cpu := byType["n2d-standard-2"] + assert.Equal(t, "asia-south1", cpu.Location) + assert.Equal(t, "asia-south1-a", cpu.SubLocation) + assert.Equal(t, []string{"asia-south1", "us-west2"}, cpu.AvailableLocations) + + gpu := byType["g5.xlarge"] + assert.Equal(t, "us-east-1", gpu.Location) + assert.Equal(t, []string{"us-east-1", "us-west-2"}, gpu.AvailableLocations) +} + +func TestFilterByLocation(t *testing.T) { + instances := ProcessInstances(locationCatalog().Items) + + t.Run("empty location is a no-op", func(t *testing.T) { + assert.Equal(t, instances, FilterByLocation(instances, "")) + }) + + t.Run("keeps types available in the location and reports it as their location", func(t *testing.T) { + got := FilterByLocation(instances, "us-west2") + require.Len(t, got, 1) + assert.Equal(t, "n2d-standard-2", got[0].Type) + assert.Equal(t, "us-west2", got[0].Location) + assert.Empty(t, got[0].SubLocation, "the default sub-location belongs to the default location") + }) + + t.Run("match is exact", func(t *testing.T) { + assert.Empty(t, FilterByLocation(instances, "us-west")) + assert.Empty(t, FilterByLocation(instances, "US-WEST2")) + }) + + t.Run("does not modify the input", func(t *testing.T) { + FilterByLocation(instances, "us-west2") + for _, inst := range instances { + if inst.Type == "n2d-standard-2" { + assert.Equal(t, "asia-south1", inst.Location) + } + } + }) +} + +func TestSearchCommandLocation(t *testing.T) { + run := func(args ...string) string { + store := &trackingStore{Response: locationCatalog()} + cmd := NewCmdGPUSearch(terminal.New(), store) + cmd.SetArgs(args) + return captureStdout(t, func() { require.NoError(t, cmd.Execute()) }) + } + types := func(out string) []string { + var got []GPUInstanceInfo + require.NoError(t, json.Unmarshal([]byte(out), &got)) + var names []string + for _, inst := range got { + names = append(names, inst.Type) + } + return names + } + + t.Run("cpu JSON includes default location fields", func(t *testing.T) { + var got []map[string]any + require.NoError(t, json.Unmarshal([]byte(run("cpu", "--json")), &got)) + byType := map[string]map[string]any{} + for _, inst := range got { + byType[fmt.Sprint(inst["type"])] = inst + } + assert.Equal(t, "asia-south1", byType["n2d-standard-2"]["location"]) + assert.Equal(t, "asia-south1-a", byType["n2d-standard-2"]["sub_location"]) + assert.Equal(t, []any{"asia-south1", "us-west2"}, byType["n2d-standard-2"]["available_locations"]) + assert.NotContains(t, byType["cpu-no-location"], "location", "location fields are omitted when unknown") + assert.NotContains(t, byType["cpu-no-location"], "available_locations") + }) + + t.Run("cpu --location filters", func(t *testing.T) { + assert.Equal(t, []string{"n2d-standard-2"}, types(run("cpu", "--location", "us-west2", "--json"))) + }) + + t.Run("gpu --location filters on the parent and the gpu subcommand", func(t *testing.T) { + assert.Equal(t, []string{"g5.xlarge"}, types(run("--location", "us-west-2", "--json"))) + assert.Equal(t, []string{"g5.xlarge"}, types(run("gpu", "--location", "us-west-2", "--json"))) + }) + + t.Run("no match reports empty results", func(t *testing.T) { + assert.Equal(t, "[]\n", run("cpu", "--location", "mars-1", "--json")) + }) + + t.Run("piped cpu table keeps TYPE and TARGET_DISK first and adds LOCATION", func(t *testing.T) { + lines := strings.Split(strings.TrimSpace(run("cpu", "--location", "us-west2")), "\n") + require.Len(t, lines, 2) + assert.Equal(t, []string{"TYPE", "TARGET_DISK", "PROVIDER", "LOCATION"}, strings.Fields(lines[0])[:4]) + row := strings.Fields(lines[1]) + assert.Equal(t, "n2d-standard-2", row[0]) + assert.Equal(t, "us-west2", row[3]) + }) + + t.Run("piped tables show the default location, or - when unknown", func(t *testing.T) { + locations := map[string]string{} + for _, kind := range []string{"gpu", "cpu"} { + lines := strings.Split(strings.TrimSpace(run(kind)), "\n") + assert.Equal(t, []string{"TYPE", "TARGET_DISK", "PROVIDER", "LOCATION"}, strings.Fields(lines[0])[:4]) + for _, line := range lines[1:] { + fields := strings.Fields(line) + locations[fields[0]] = fields[3] + } + } + assert.Equal(t, "us-east-1", locations["g5.xlarge"]) + assert.Equal(t, "asia-south1", locations["n2d-standard-2"]) + assert.Equal(t, "-", locations["cpu-no-location"]) + }) +} + +func TestLocationColumnInEveryTable(t *testing.T) { + instances := ProcessInstances(locationCatalog().Items) + var gpus, cpus []GPUInstanceInfo + for _, inst := range instances { + if inst.Manufacturer == "cpu" { + cpus = append(cpus, inst) + } else { + gpus = append(gpus, inst) + } + } + term := terminal.New() + tables := map[string]func(){ + "gpu": func() { displayGPUTable(term, gpus) }, + "gpu plain": func() { displayGPUTablePlain(gpus) }, + "gpu wide": func() { displayGPUTableWide(term, gpus) }, + "gpu plain wide": func() { displayGPUTablePlainWide(gpus) }, + "cpu": func() { displayCPUTable(cpus) }, + "cpu plain": func() { displayCPUTablePlain(cpus) }, + "cpu no location": func() { displayCPUTablePlain(cpus[len(cpus)-1:]) }, + } + for name, render := range tables { + t.Run(name, func(t *testing.T) { + out := captureStdout(t, render) + assert.Contains(t, out, "LOCATION") + if name == "cpu no location" { + assert.Equal(t, "-", strings.Fields(strings.Split(strings.TrimSpace(out), "\n")[1])[3]) + } else { + assert.Contains(t, out, "us-east-1") + } + }) + } +} diff --git a/pkg/cmd/gpusearch/locations.go b/pkg/cmd/gpusearch/locations.go new file mode 100644 index 00000000..19f26885 --- /dev/null +++ b/pkg/cmd/gpusearch/locations.go @@ -0,0 +1,154 @@ +package gpusearch + +import ( + "encoding/json" + "fmt" + "os" + "slices" + "strings" + + breverrors "github.com/brevdev/brev-cli/pkg/errors" + "github.com/brevdev/brev-cli/pkg/terminal" + "github.com/jedib0t/go-pretty/v6/table" + "github.com/spf13/cobra" +) + +const locationsExample = ` + # List every location and how many types can be created there + brev search locations + + # Where can a type be created? + brev search locations --type n2d-standard-2 + + # Locations for one provider + brev search locations --provider aws + + # Then search or create in a location + brev search cpu --location us-west2 + brev create my-instance --type n2d-standard-2 --location us-west2 +` + +// LocationInfo summarizes the instance types that can be created in a location. +type LocationInfo struct { + Location string `json:"location"` + Providers []string `json:"providers"` + GPUTypes int `json:"gpu_types"` + CPUTypes int `json:"cpu_types"` +} + +func newCmdLocationsSubcommand(t *terminal.Terminal, store GPUSearchStore) *cobra.Command { + var instanceType, provider string + var jsonOutput bool + + cmd := &cobra.Command{ + Use: "locations", + DisableFlagsInUseLine: true, + Short: "List locations that instance types can be created in", + Long: `List the locations that instance types can be created in, with how many GPU +and CPU types are available in each. Pass a location to 'brev search --location' +or 'brev create --location'.`, + Example: locationsExample, + RunE: func(cmd *cobra.Command, args []string) error { + return RunLocationSearch(t, store, instanceType, provider, jsonOutput) + }, + } + + cmd.Flags().StringVar(&instanceType, "type", "", "Only show locations this instance type can be created in (exact match)") + cmd.Flags().StringVarP(&provider, "provider", "p", "", "Filter by provider/cloud (case-insensitive, partial match)") + cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output results as JSON") + + return cmd +} + +// RunLocationSearch lists the locations of the instance types that match the filters. +func RunLocationSearch(t *terminal.Terminal, store GPUSearchStore, instanceType, provider string, jsonOutput bool) error { + response, err := store.GetInstanceTypes(true) + if err != nil { + return breverrors.WrapAndTrace(err) + } + var items []InstanceType + if response != nil { + items = response.Items + } + + // The same filtering as 'brev search gpu' and 'brev search cpu', so the + // counts match what those commands list with --location. + instances := FilterInstances(ProcessInstances(items), "", provider, "", 0, 0, 0, 0, 0, 0, 0, false, false, false, false) + if instanceType != "" { + instances = slices.DeleteFunc(instances, func(inst GPUInstanceInfo) bool { return inst.Type != instanceType }) + } + + locations := SummarizeLocations(instances) + if len(locations) == 0 { + return displayEmptyResults(t, "No locations match the specified filters", jsonOutput, IsStdoutPiped()) + } + if jsonOutput { + output, err := json.MarshalIndent(locations, "", " ") + if err != nil { + return breverrors.WrapAndTrace(err) + } + fmt.Println(string(output)) + return nil + } + + ta := table.NewWriter() + ta.SetOutputMirror(os.Stdout) + ta.Style().Options = getBrevTableOptions() + ta.AppendHeader(table.Row{"LOCATION", "PROVIDERS", "GPU_TYPES", "CPU_TYPES"}) + for _, loc := range locations { + ta.AppendRow(table.Row{loc.Location, joinOrDash(loc.Providers), loc.GPUTypes, loc.CPUTypes}) + } + ta.Render() + if !IsStdoutPiped() { + t.Vprintf("\n%s\n", t.Green(fmt.Sprintf("Found %d locations", len(locations)))) + } + return nil +} + +// SummarizeLocations groups instances by every location they are available +// in, counting distinct GPU and CPU types. Results are sorted by location. +func SummarizeLocations(instances []GPUInstanceInfo) []LocationInfo { + type typeSets struct{ gpu, cpu, providers map[string]bool } + byLocation := map[string]*typeSets{} + for _, inst := range instances { + for _, location := range inst.AvailableLocations { + sets := byLocation[location] + if sets == nil { + sets = &typeSets{gpu: map[string]bool{}, cpu: map[string]bool{}, providers: map[string]bool{}} + byLocation[location] = sets + } + if inst.Manufacturer == "cpu" { + sets.cpu[inst.Type] = true + } else { + sets.gpu[inst.Type] = true + } + if inst.Provider != "" { + sets.providers[inst.Provider] = true + } + } + } + + locations := make([]LocationInfo, 0, len(byLocation)) + for location, sets := range byLocation { + providers := make([]string, 0, len(sets.providers)) + for p := range sets.providers { + providers = append(providers, p) + } + slices.Sort(providers) + locations = append(locations, LocationInfo{ + Location: location, + Providers: providers, + GPUTypes: len(sets.gpu), + CPUTypes: len(sets.cpu), + }) + } + slices.SortFunc(locations, func(a, b LocationInfo) int { return strings.Compare(a.Location, b.Location) }) + return locations +} + +func joinOrDash(values []string) string { + if len(values) == 0 { + return "-" + } + return strings.Join(values, ",") +} diff --git a/pkg/cmd/gpusearch/locations_test.go b/pkg/cmd/gpusearch/locations_test.go new file mode 100644 index 00000000..069a996e --- /dev/null +++ b/pkg/cmd/gpusearch/locations_test.go @@ -0,0 +1,119 @@ +package gpusearch + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/brevdev/brev-cli/pkg/terminal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSummarizeLocations(t *testing.T) { + instances := ProcessInstances([]InstanceType{ + {Type: "cpu-a", Provider: "gcp", AvailableLocations: []string{"us-west2", "asia-south1"}}, + {Type: "cpu-b", Provider: "aws", AvailableLocations: []string{"us-west2"}}, + { + // Two GPU entries produce two rows; the type is counted once. + Type: "gpu-a", Provider: "gcp", AvailableLocations: []string{"us-west2"}, + SupportedGPUs: []GPU{{Count: 1, Name: "L4", Manufacturer: "NVIDIA"}, {Count: 2, Name: "L4", Manufacturer: "NVIDIA"}}, + }, + {Type: "cpu-c", Provider: "nebius", AvailableLocations: []string{"us-west2"}}, + {Type: "cpu-d", Provider: "lambda", AvailableLocations: []string{"us-west2"}}, + {Type: "no-provider", AvailableLocations: []string{"unknown-1"}}, + {Type: "no-locations", Provider: "aws"}, + }) + + want := []LocationInfo{ + {Location: "asia-south1", Providers: []string{"gcp"}, GPUTypes: 0, CPUTypes: 1}, + {Location: "unknown-1", Providers: []string{}, GPUTypes: 0, CPUTypes: 1}, + {Location: "us-west2", Providers: []string{"aws", "gcp", "lambda", "nebius"}, GPUTypes: 1, CPUTypes: 4}, + } + for range 5 { // map iteration order varies between runs + assert.Equal(t, want, SummarizeLocations(instances)) + } + assert.Empty(t, SummarizeLocations(nil)) +} + +func TestLocationsTableShowsDashForUnknownProvider(t *testing.T) { + store := &trackingStore{Response: &InstanceTypesResponse{Items: []InstanceType{ + {Type: "no-provider", AvailableLocations: []string{"unknown-1"}}, + }}} + cmd := NewCmdGPUSearch(terminal.New(), store) + cmd.SetArgs([]string{"locations"}) + out := captureStdout(t, func() { require.NoError(t, cmd.Execute()) }) + lines := strings.Split(strings.TrimSpace(out), "\n") + require.Len(t, lines, 2) + assert.Equal(t, []string{"unknown-1", "-", "0", "1"}, strings.Fields(lines[1])) +} + +func TestSearchLocationsCommand(t *testing.T) { + catalog := locationCatalog() + catalog.Items = append(catalog.Items, InstanceType{ + Type: "amd-gpu", Provider: "aws", AvailableLocations: []string{"us-east-1"}, + SupportedGPUs: []GPU{{Count: 1, Name: "MI300X", Manufacturer: "AMD"}}, + }) + run := func(args ...string) (string, *trackingStore) { + store := &trackingStore{Response: catalog} + cmd := NewCmdGPUSearch(terminal.New(), store) + cmd.SetArgs(append([]string{"locations"}, args...)) + return captureStdout(t, func() { require.NoError(t, cmd.Execute()) }), store + } + parse := func(out string) []LocationInfo { + var got []LocationInfo + require.NoError(t, json.Unmarshal([]byte(out), &got)) + return got + } + + t.Run("lists every location with GPU and CPU type counts", func(t *testing.T) { + out, store := run("--json") + assert.Equal(t, []bool{true}, store.calls, "needs the catalog with CPU types") + assert.Equal(t, []LocationInfo{ + {Location: "asia-south1", Providers: []string{"gcp"}, GPUTypes: 0, CPUTypes: 1}, + {Location: "us-east-1", Providers: []string{"aws"}, GPUTypes: 1, CPUTypes: 1}, + {Location: "us-west-2", Providers: []string{"aws"}, GPUTypes: 1, CPUTypes: 0}, + {Location: "us-west2", Providers: []string{"gcp"}, GPUTypes: 0, CPUTypes: 1}, + }, parse(out), "non-NVIDIA GPUs are excluded, as in 'brev search gpu'") + }) + + t.Run("--type lists where one type can be created", func(t *testing.T) { + out, _ := run("--type", "n2d-standard-2", "--json") + var locations []string + for _, loc := range parse(out) { + locations = append(locations, loc.Location) + } + assert.Equal(t, []string{"asia-south1", "us-west2"}, locations) + }) + + t.Run("--provider filters", func(t *testing.T) { + out, _ := run("--provider", "gcp", "--json") + for _, loc := range parse(out) { + assert.Equal(t, []string{"gcp"}, loc.Providers) + } + assert.Len(t, parse(out), 2) + }) + + t.Run("no match reports empty results", func(t *testing.T) { + out, _ := run("--type", "does-not-exist", "--json") + assert.Equal(t, "[]\n", out) + }) + + t.Run("piped table", func(t *testing.T) { + out, _ := run() + lines := strings.Split(strings.TrimSpace(out), "\n") + require.Len(t, lines, 5) + assert.Equal(t, []string{"LOCATION", "PROVIDERS", "GPU_TYPES", "CPU_TYPES"}, strings.Fields(lines[0])) + assert.Equal(t, []string{"us-east-1", "aws", "1", "1"}, strings.Fields(lines[2])) + }) + + t.Run("counts match search --location", func(t *testing.T) { + out, _ := run("--json") + for _, loc := range parse(out) { + gpus, _ := searchTypes(t, "gpu", "--location", loc.Location) + cpus, _ := searchTypes(t, "cpu", "--location", loc.Location) + assert.Len(t, gpus, loc.GPUTypes, "GPU types in %s", loc.Location) + assert.Len(t, cpus, loc.CPUTypes, "CPU types in %s", loc.Location) + } + }) +}