Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 139 additions & 55 deletions pkg/cmd/gpucreate/gpucreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand Down
Loading
Loading