2022-02-12 13:34:04 -06:00
package cli
import (
2023-02-27 10:18:19 -06:00
"context"
2022-02-12 13:34:04 -06:00
"fmt"
2022-09-22 13:26:05 -05:00
"io"
2022-02-12 13:34:04 -06:00
"time"
2023-04-04 14:22:46 +02:00
"github.com/google/uuid"
2022-04-14 13:23:20 -04:00
"golang.org/x/exp/slices"
2022-02-12 13:34:04 -06:00
"golang.org/x/xerrors"
2023-03-23 17:42:20 -05:00
"github.com/coder/coder/cli/clibase"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/cli/cliui"
2022-06-02 11:23:34 +01:00
"github.com/coder/coder/coderd/util/ptr"
2023-08-09 14:50:26 -05:00
"github.com/coder/coder/coderd/util/slice"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/codersdk"
2022-02-12 13:34:04 -06:00
)
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) create () * clibase . Cmd {
2022-03-22 13:17:50 -06:00
var (
2023-08-09 13:00:25 +02:00
templateName string
startAt string
stopAfter time . Duration
workspaceName string
parameterFlags workspaceParameterFlags
2022-03-22 13:17:50 -06:00
)
2023-03-23 17:42:20 -05:00
client := new ( codersdk . Client )
cmd := & clibase . Cmd {
2022-05-09 17:42:02 -05:00
Annotations : workspaceCommand ,
Use : "create [name]" ,
2022-09-19 11:36:18 -05:00
Short : "Create a workspace" ,
2023-07-14 09:48:02 -04:00
Long : formatExamples (
example {
Description : "Create a workspace for another user (if you have permission)" ,
Command : "coder create <username>/<workspace_name>" ,
},
),
Middleware : clibase . Chain ( r . InitClient ( client )),
2023-03-23 17:42:20 -05:00
Handler : func ( inv * clibase . Invocation ) error {
organization , err := CurrentOrganization ( inv , client )
2022-02-12 13:34:04 -06:00
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2023-07-14 09:48:02 -04:00
workspaceOwner := codersdk . Me
2023-03-23 17:42:20 -05:00
if len ( inv . Args ) >= 1 {
2023-07-14 09:48:02 -04:00
workspaceOwner , workspaceName , err = splitNamedWorkspace ( inv . Args [ 0 ])
if err != nil {
return err
}
2022-02-12 13:34:04 -06:00
}
2022-04-11 18:54:30 -05:00
if workspaceName == "" {
2023-03-23 17:42:20 -05:00
workspaceName , err = cliui . Prompt ( inv , cliui . PromptOptions {
2022-04-11 18:54:30 -05:00
Text : "Specify a name for your workspace:" ,
Validate : func ( workspaceName string ) error {
2023-03-23 17:42:20 -05:00
_ , err = client . WorkspaceByOwnerAndName ( inv . Context (), codersdk . Me , workspaceName , codersdk . WorkspaceOptions {})
2022-04-11 18:54:30 -05:00
if err == nil {
return xerrors . Errorf ( "A workspace already exists named %q!" , workspaceName )
}
return nil
},
})
if err != nil {
return err
}
}
2022-02-12 13:34:04 -06:00
2023-07-14 09:48:02 -04:00
_ , err = client . WorkspaceByOwnerAndName ( inv . Context (), workspaceOwner , workspaceName , codersdk . WorkspaceOptions {})
2022-03-22 13:17:50 -06:00
if err == nil {
return xerrors . Errorf ( "A workspace already exists named %q!" , workspaceName )
2022-02-12 13:34:04 -06:00
}
2022-03-22 13:17:50 -06:00
2022-04-14 13:23:20 -04:00
var template codersdk . Template
if templateName == "" {
2023-06-07 00:22:58 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout , cliui . DefaultStyles . Wrap . Render ( "Select a template below to preview the provisioned infrastructure:" ))
2022-04-14 13:23:20 -04:00
2023-03-23 17:42:20 -05:00
templates , err := client . TemplatesByOrganization ( inv . Context (), organization . ID )
2022-04-14 13:23:20 -04:00
if err != nil {
return err
}
2023-08-09 14:50:26 -05:00
slices . SortFunc ( templates , func ( a , b codersdk . Template ) int {
return slice . Descending ( a . ActiveUserCount , b . ActiveUserCount )
2022-04-14 13:23:20 -04:00
})
templateNames := make ([] string , 0 , len ( templates ))
templateByName := make ( map [ string ] codersdk . Template , len ( templates ))
for _ , template := range templates {
templateName := template . Name
2022-09-09 14:30:31 -05:00
if template . ActiveUserCount > 0 {
2023-06-07 00:22:58 -05:00
templateName += cliui . DefaultStyles . Placeholder . Render (
2022-09-09 14:30:31 -05:00
fmt . Sprintf (
" (used by %s)" ,
formatActiveDevelopers ( template . ActiveUserCount ),
),
)
2022-04-14 13:23:20 -04:00
}
templateNames = append ( templateNames , templateName )
templateByName [ templateName ] = template
}
// Move the cursor up a single line for nicer display!
2023-03-23 17:42:20 -05:00
option , err := cliui . Select ( inv , cliui . SelectOptions {
2022-04-14 13:23:20 -04:00
Options : templateNames ,
HideSearch : true ,
})
if err != nil {
return err
}
template = templateByName [ option ]
} else {
2023-03-23 17:42:20 -05:00
template , err = client . TemplateByName ( inv . Context (), organization . ID , templateName )
2022-04-14 13:23:20 -04:00
if err != nil {
return xerrors . Errorf ( "get template by name: %w" , err )
}
}
2022-06-17 21:38:10 +01:00
var schedSpec * string
if startAt != "" {
sched , err := parseCLISchedule ( startAt )
if err != nil {
return err
}
schedSpec = ptr . Ref ( sched . String ())
2022-06-07 13:37:45 +01:00
}
2023-08-09 13:00:25 +02:00
cliRichParameters , err := asWorkspaceBuildParameters ( parameterFlags . richParameters )
if err != nil {
return xerrors . Errorf ( "can't parse given parameter values: %w" , err )
}
richParameters , err := prepWorkspaceBuild ( inv , client , prepWorkspaceBuildArgs {
Action : WorkspaceCreate ,
Template : template ,
NewWorkspaceName : workspaceName ,
RichParameterFile : parameterFlags . richParameterFile ,
RichParameters : cliRichParameters ,
2022-04-11 18:54:30 -05:00
})
2022-02-12 13:34:04 -06:00
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "prepare build: %w" , err )
2022-02-12 13:34:04 -06:00
}
2023-03-23 17:42:20 -05:00
_ , err = cliui . Prompt ( inv , cliui . PromptOptions {
2022-04-11 18:54:30 -05:00
Text : "Confirm create?" ,
2022-02-12 13:34:04 -06:00
IsConfirm : true ,
})
if err != nil {
return err
}
2023-03-17 18:14:46 +01:00
var ttlMillis * int64
if stopAfter > 0 {
ttlMillis = ptr . Ref ( stopAfter . Milliseconds ())
}
2023-07-14 09:48:02 -04:00
workspace , err := client . CreateWorkspace ( inv . Context (), organization . ID , workspaceOwner , codersdk . CreateWorkspaceRequest {
2023-01-23 15:01:22 +01:00
TemplateID : template . ID ,
Name : workspaceName ,
AutostartSchedule : schedSpec ,
2023-03-17 18:14:46 +01:00
TTLMillis : ttlMillis ,
2023-08-09 13:00:25 +02:00
RichParameterValues : richParameters ,
2022-02-12 13:34:04 -06:00
})
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "create workspace: %w" , err )
2022-02-12 13:34:04 -06:00
}
2022-04-14 13:23:20 -04:00
2023-03-23 17:42:20 -05:00
err = cliui . WorkspaceBuild ( inv . Context (), inv . Stdout , client , workspace . LatestBuild . ID )
2022-04-11 18:54:30 -05:00
if err != nil {
2023-03-23 17:42:20 -05:00
return xerrors . Errorf ( "watch build: %w" , err )
2022-04-11 18:54:30 -05:00
}
2022-04-14 13:23:20 -04:00
2023-06-07 00:22:58 -05:00
_ , _ = fmt . Fprintf ( inv . Stdout , "\nThe %s workspace has been created at %s!\n" , cliui . DefaultStyles . Keyword . Render ( workspace . Name ), cliui . DefaultStyles . DateTimeStamp . Render ( time . Now (). Format ( time . Stamp )))
2022-04-11 18:54:30 -05:00
return nil
2022-02-12 13:34:04 -06:00
},
}
2023-03-23 17:42:20 -05:00
cmd . Options = append ( cmd . Options ,
clibase . Option {
Flag : "template" ,
FlagShorthand : "t" ,
Env : "CODER_TEMPLATE_NAME" ,
Description : "Specify a template name." ,
Value : clibase . StringOf ( & templateName ),
},
clibase . Option {
Flag : "start-at" ,
Env : "CODER_WORKSPACE_START_AT" ,
Description : "Specify the workspace autostart schedule. Check coder schedule start --help for the syntax." ,
Value : clibase . StringOf ( & startAt ),
},
clibase . Option {
Flag : "stop-after" ,
Env : "CODER_WORKSPACE_STOP_AFTER" ,
Description : "Specify a duration after which the workspace should shut down (e.g. 8h)." ,
Value : clibase . DurationOf ( & stopAfter ),
},
cliui . SkipPromptOption (),
)
2023-08-09 13:00:25 +02:00
cmd . Options = append ( cmd . Options , parameterFlags . cliParameters () ... )
2022-02-12 13:34:04 -06:00
return cmd
}
2022-06-27 11:19:10 -05:00
type prepWorkspaceBuildArgs struct {
2023-08-09 13:00:25 +02:00
Action WorkspaceCLIAction
Template codersdk . Template
NewWorkspaceName string
WorkspaceID uuid . UUID
2023-01-23 15:01:22 +01:00
2023-08-09 13:00:25 +02:00
LastBuildParameters [] codersdk . WorkspaceBuildParameter
2023-01-23 15:01:22 +01:00
2023-08-09 13:00:25 +02:00
PromptBuildOptions bool
BuildOptions [] codersdk . WorkspaceBuildParameter
PromptRichParameters bool
RichParameters [] codersdk . WorkspaceBuildParameter
RichParameterFile string
2022-06-27 11:19:10 -05:00
}
// prepWorkspaceBuild will ensure a workspace build will succeed on the latest template version.
2023-08-09 13:00:25 +02:00
// Any missing params will be prompted to the user. It supports rich parameters.
func prepWorkspaceBuild ( inv * clibase . Invocation , client * codersdk . Client , args prepWorkspaceBuildArgs ) ([] codersdk . WorkspaceBuildParameter , error ) {
2023-03-23 17:42:20 -05:00
ctx := inv . Context ()
2023-02-02 16:44:57 +01:00
2022-06-27 11:19:10 -05:00
templateVersion , err := client . TemplateVersion ( ctx , args . Template . ActiveVersionID )
if err != nil {
2023-08-09 13:00:25 +02:00
return nil , xerrors . Errorf ( "get template version: %w" , err )
2022-06-27 11:19:10 -05:00
}
2023-01-23 15:01:22 +01:00
2023-03-23 17:42:20 -05:00
templateVersionParameters , err := client . TemplateVersionRichParameters ( inv . Context (), templateVersion . ID )
2023-01-23 15:01:22 +01:00
if err != nil {
return nil , xerrors . Errorf ( "get template version rich parameters: %w" , err )
}
2023-08-09 13:00:25 +02:00
parameterFile := map [ string ] string {}
2023-01-23 15:01:22 +01:00
if args . RichParameterFile != "" {
2023-08-09 13:00:25 +02:00
parameterFile , err = parseParameterMapFile ( args . RichParameterFile )
2023-01-23 15:01:22 +01:00
if err != nil {
2023-08-09 13:00:25 +02:00
return nil , xerrors . Errorf ( "can't parse parameter map file: %w" , err )
2023-01-23 15:01:22 +01:00
}
}
2023-07-13 12:56:02 +02:00
2023-08-09 13:00:25 +02:00
resolver := new ( ParameterResolver ).
WithLastBuildParameters ( args . LastBuildParameters ).
WithPromptBuildOptions ( args . PromptBuildOptions ).
WithBuildOptions ( args . BuildOptions ).
WithPromptRichParameters ( args . PromptRichParameters ).
WithRichParameters ( args . RichParameters ).
WithRichParametersFile ( parameterFile )
buildParameters , err := resolver . Resolve ( inv , args . Action , templateVersionParameters )
if err != nil {
return nil , err
2023-01-23 15:01:22 +01:00
}
2022-06-27 11:19:10 -05:00
2023-03-23 17:42:20 -05:00
err = cliui . GitAuth ( ctx , inv . Stdout , cliui . GitAuthOptions {
2023-02-27 10:18:19 -06:00
Fetch : func ( ctx context . Context ) ([] codersdk . TemplateVersionGitAuth , error ) {
return client . TemplateVersionGitAuth ( ctx , templateVersion . ID )
},
})
if err != nil {
return nil , xerrors . Errorf ( "template version git auth: %w" , err )
}
2022-06-27 11:19:10 -05:00
// Run a dry-run with the given parameters to check correctness
2023-03-23 17:42:20 -05:00
dryRun , err := client . CreateTemplateVersionDryRun ( inv . Context (), templateVersion . ID , codersdk . CreateTemplateVersionDryRunRequest {
2023-01-23 15:01:22 +01:00
WorkspaceName : args . NewWorkspaceName ,
2023-08-09 13:00:25 +02:00
RichParameterValues : buildParameters ,
2022-06-27 11:19:10 -05:00
})
if err != nil {
return nil , xerrors . Errorf ( "begin workspace dry-run: %w" , err )
}
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( inv . Stdout , "Planning workspace..." )
err = cliui . ProvisionerJob ( inv . Context (), inv . Stdout , cliui . ProvisionerJobOptions {
2022-06-27 11:19:10 -05:00
Fetch : func () ( codersdk . ProvisionerJob , error ) {
2023-03-23 17:42:20 -05:00
return client . TemplateVersionDryRun ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
},
Cancel : func () error {
2023-03-23 17:42:20 -05:00
return client . CancelTemplateVersionDryRun ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
},
2022-09-22 13:26:05 -05:00
Logs : func () ( <- chan codersdk . ProvisionerJobLog , io . Closer , error ) {
2023-03-23 17:42:20 -05:00
return client . TemplateVersionDryRunLogsAfter ( inv . Context (), templateVersion . ID , dryRun . ID , 0 )
2022-06-27 11:19:10 -05:00
},
// Don't show log output for the dry-run unless there's an error.
Silent : true ,
})
if err != nil {
// TODO (Dean): reprompt for parameter values if we deem it to
// be a validation error
return nil , xerrors . Errorf ( "dry-run workspace: %w" , err )
}
2023-03-23 17:42:20 -05:00
resources , err := client . TemplateVersionDryRunResources ( inv . Context (), templateVersion . ID , dryRun . ID )
2022-06-27 11:19:10 -05:00
if err != nil {
return nil , xerrors . Errorf ( "get workspace dry-run resources: %w" , err )
}
2023-03-23 17:42:20 -05:00
err = cliui . WorkspaceResources ( inv . Stdout , resources , cliui . WorkspaceResourcesOptions {
2022-06-27 11:19:10 -05:00
WorkspaceName : args . NewWorkspaceName ,
// Since agents haven't connected yet, hiding this makes more sense.
HideAgentState : true ,
Title : "Workspace Preview" ,
})
if err != nil {
2023-03-23 17:42:20 -05:00
return nil , xerrors . Errorf ( "get resources: %w" , err )
2022-06-27 11:19:10 -05:00
}
2023-08-09 13:00:25 +02:00
return buildParameters , nil
2023-04-04 14:22:46 +02:00
}