2022-02-12 13:34:04 -06:00
package cli
import (
"fmt"
2022-09-22 13:26:05 -05:00
"io"
2022-02-12 13:34:04 -06:00
"time"
"github.com/spf13/cobra"
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"
2022-04-11 18:54:30 -05:00
"github.com/coder/coder/cli/cliflag"
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"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/codersdk"
2022-02-12 13:34:04 -06:00
)
2022-05-02 11:08:52 -05:00
func create () * cobra . Command {
2022-03-22 13:17:50 -06:00
var (
2022-06-17 21:38:10 +01:00
parameterFile string
templateName string
startAt string
stopAfter time . Duration
workspaceName string
2022-03-22 13:17:50 -06:00
)
2022-02-12 13:34:04 -06:00
cmd := & cobra . Command {
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" ,
2022-02-12 13:34:04 -06:00
RunE : func ( cmd * cobra . Command , args [] string ) error {
2022-08-23 13:55:39 -07:00
client , err := CreateClient ( cmd )
2022-02-12 13:34:04 -06:00
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2022-10-27 16:49:35 -05:00
organization , err := CurrentOrganization ( cmd , client )
2022-02-12 13:34:04 -06:00
if err != nil {
return err
}
2022-04-11 18:54:30 -05:00
if len ( args ) >= 1 {
2022-04-14 13:23:20 -04:00
workspaceName = args [ 0 ]
2022-02-12 13:34:04 -06:00
}
2022-04-11 18:54:30 -05:00
if workspaceName == "" {
workspaceName , err = cliui . Prompt ( cmd , cliui . PromptOptions {
Text : "Specify a name for your workspace:" ,
Validate : func ( workspaceName string ) error {
2022-06-10 09:58:42 -05:00
_ , err = client . WorkspaceByOwnerAndName ( cmd . 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
2022-06-10 09:58:42 -05:00
_ , err = client . WorkspaceByOwnerAndName ( cmd . Context (), codersdk . Me , 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 == "" {
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Wrap . Render ( "Select a template below to preview the provisioned infrastructure:" ))
templates , err := client . TemplatesByOrganization ( cmd . Context (), organization . ID )
if err != nil {
return err
}
slices . SortFunc ( templates , func ( a , b codersdk . Template ) bool {
2022-09-09 14:30:31 -05:00
return 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 {
templateName += cliui . Styles . Placeholder . Render (
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!
option , err := cliui . Select ( cmd , cliui . SelectOptions {
Options : templateNames ,
HideSearch : true ,
})
if err != nil {
return err
}
template = templateByName [ option ]
} else {
template , err = client . TemplateByName ( cmd . Context (), organization . ID , templateName )
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
}
2022-06-27 11:19:10 -05:00
parameters , err := prepWorkspaceBuild ( cmd , client , prepWorkspaceBuildArgs {
Template : template ,
ExistingParams : [] codersdk . Parameter {},
ParameterFile : parameterFile ,
NewWorkspaceName : workspaceName ,
2022-04-11 18:54:30 -05:00
})
2022-02-12 13:34:04 -06:00
if err != nil {
return err
}
2022-03-22 13:17:50 -06:00
_ , err = cliui . Prompt ( cmd , 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
}
2022-09-23 20:17:10 -05:00
workspace , err := client . CreateWorkspace ( cmd . Context (), organization . ID , codersdk . Me , codersdk . CreateWorkspaceRequest {
2022-05-23 23:31:41 +01:00
TemplateID : template . ID ,
Name : workspaceName ,
2022-06-07 13:37:45 +01:00
AutostartSchedule : schedSpec ,
2022-06-17 21:38:10 +01:00
TTLMillis : ptr . Ref ( stopAfter . Milliseconds ()),
2022-05-23 23:31:41 +01:00
ParameterValues : parameters ,
2022-02-12 13:34:04 -06:00
})
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2022-11-06 18:50:34 -08:00
err = cliui . WorkspaceBuild ( cmd . Context (), cmd . OutOrStdout (), client , workspace . LatestBuild . ID )
2022-04-11 18:54:30 -05:00
if err != nil {
return err
}
2022-04-14 13:23:20 -04:00
2022-07-08 14:27:56 -05:00
_ , _ = fmt . Fprintf ( cmd . OutOrStdout (), "\nThe %s workspace has been created at %s!\n" , cliui . Styles . Keyword . Render ( workspace . Name ), cliui . Styles . 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
},
}
2022-05-20 10:59:04 -05:00
cliui . AllowSkipPrompt ( cmd )
2022-04-14 13:23:20 -04:00
cliflag . StringVarP ( cmd . Flags (), & templateName , "template" , "t" , "CODER_TEMPLATE_NAME" , "" , "Specify a template name." )
2022-05-20 11:29:10 -04:00
cliflag . StringVarP ( cmd . Flags (), & parameterFile , "parameter-file" , "" , "CODER_PARAMETER_FILE" , "" , "Specify a file path with parameter values." )
2022-06-17 21:38:10 +01:00
cliflag . StringVarP ( cmd . Flags (), & startAt , "start-at" , "" , "CODER_WORKSPACE_START_AT" , "" , "Specify the workspace autostart schedule. Check `coder schedule start --help` for the syntax." )
cliflag . DurationVarP ( cmd . Flags (), & stopAfter , "stop-after" , "" , "CODER_WORKSPACE_STOP_AFTER" , 8 * time . Hour , "Specify a duration after which the workspace should shut down (e.g. 8h)." )
2022-02-12 13:34:04 -06:00
return cmd
}
2022-06-27 11:19:10 -05:00
type prepWorkspaceBuildArgs struct {
Template codersdk . Template
ExistingParams [] codersdk . Parameter
ParameterFile string
NewWorkspaceName string
}
// prepWorkspaceBuild will ensure a workspace build will succeed on the latest template version.
// Any missing params will be prompted to the user.
func prepWorkspaceBuild ( cmd * cobra . Command , client * codersdk . Client , args prepWorkspaceBuildArgs ) ([] codersdk . CreateParameterRequest , error ) {
ctx := cmd . Context ()
templateVersion , err := client . TemplateVersion ( ctx , args . Template . ActiveVersionID )
if err != nil {
return nil , err
}
parameterSchemas , err := client . TemplateVersionSchema ( ctx , templateVersion . ID )
if err != nil {
return nil , err
}
// parameterMapFromFile can be nil if parameter file is not specified
var parameterMapFromFile map [ string ] string
useParamFile := false
if args . ParameterFile != "" {
useParamFile = true
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( "Attempting to read the variables from the parameter file." ) + "\r\n" )
parameterMapFromFile , err = createParameterMapFromFile ( args . ParameterFile )
if err != nil {
return nil , err
}
}
disclaimerPrinted := false
parameters := make ([] codersdk . CreateParameterRequest , 0 )
PromptParamLoop :
for _ , parameterSchema := range parameterSchemas {
if ! parameterSchema . AllowOverrideSource {
continue
}
if ! disclaimerPrinted {
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), cliui . Styles . Paragraph . Render ( "This template has customizable parameters. Values can be changed after create, but may have unintended side effects (like data loss)." ) + "\r\n" )
disclaimerPrinted = true
}
// Param file is all or nothing
if ! useParamFile {
for _ , e := range args . ExistingParams {
if e . Name == parameterSchema . Name {
// If the param already exists, we do not need to prompt it again.
// The workspace scope will reuse params for each build.
continue PromptParamLoop
}
}
}
parameterValue , err := getParameterValueFromMapOrInput ( cmd , parameterMapFromFile , parameterSchema )
if err != nil {
return nil , err
}
parameters = append ( parameters , codersdk . CreateParameterRequest {
Name : parameterSchema . Name ,
SourceValue : parameterValue ,
SourceScheme : codersdk . ParameterSourceSchemeData ,
DestinationScheme : parameterSchema . DefaultDestinationScheme ,
})
}
_ , _ = fmt . Fprintln ( cmd . OutOrStdout ())
// Run a dry-run with the given parameters to check correctness
dryRun , err := client . CreateTemplateVersionDryRun ( cmd . Context (), templateVersion . ID , codersdk . CreateTemplateVersionDryRunRequest {
WorkspaceName : args . NewWorkspaceName ,
ParameterValues : parameters ,
})
if err != nil {
return nil , xerrors . Errorf ( "begin workspace dry-run: %w" , err )
}
_ , _ = fmt . Fprintln ( cmd . OutOrStdout (), "Planning workspace..." )
err = cliui . ProvisionerJob ( cmd . Context (), cmd . OutOrStdout (), cliui . ProvisionerJobOptions {
Fetch : func () ( codersdk . ProvisionerJob , error ) {
return client . TemplateVersionDryRun ( cmd . Context (), templateVersion . ID , dryRun . ID )
},
Cancel : func () error {
return client . CancelTemplateVersionDryRun ( cmd . Context (), templateVersion . ID , dryRun . ID )
},
2022-09-22 13:26:05 -05:00
Logs : func () ( <- chan codersdk . ProvisionerJobLog , io . Closer , error ) {
2022-11-06 18:50:34 -08:00
return client . TemplateVersionDryRunLogsAfter ( cmd . 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 )
}
resources , err := client . TemplateVersionDryRunResources ( cmd . Context (), templateVersion . ID , dryRun . ID )
if err != nil {
return nil , xerrors . Errorf ( "get workspace dry-run resources: %w" , err )
}
err = cliui . WorkspaceResources ( cmd . OutOrStdout (), resources , cliui . WorkspaceResourcesOptions {
WorkspaceName : args . NewWorkspaceName ,
// Since agents haven't connected yet, hiding this makes more sense.
HideAgentState : true ,
Title : "Workspace Preview" ,
})
if err != nil {
return nil , err
}
return parameters , nil
}