Skip to content

feat: Allow inheriting parameters from previous template_versions when updating a template #2397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes from 11 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
14 changes: 11 additions & 3 deletions cli/parameterslist.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,23 @@ func parameterList() *cobra.Command {
}
scopeID = template.ID

case codersdk.ParameterScopeImportJob, "template_version":
scope = string(codersdk.ParameterScopeImportJob)
case codersdk.ParameterImportJob, "template_version":
scope = string(codersdk.ParameterImportJob)
scopeID, err = uuid.Parse(name)
if err != nil {
return xerrors.Errorf("%q must be a uuid for this scope type", name)
}

// Could be a template_version id or a job id. Check for the
// version id.
tv, err := client.TemplateVersion(cmd.Context(), scopeID)
if err == nil {
scopeID = tv.Job.ID
}

default:
return xerrors.Errorf("%q is an unsupported scope, use %v", scope, []codersdk.ParameterScope{
codersdk.ParameterWorkspace, codersdk.ParameterTemplate, codersdk.ParameterScopeImportJob,
codersdk.ParameterWorkspace, codersdk.ParameterTemplate, codersdk.ParameterImportJob,
})
}

Expand Down
74 changes: 64 additions & 10 deletions cli/templatecreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,13 @@ func templateCreate() *cobra.Command {
}
spin.Stop()

job, parameters, err := createValidTemplateVersion(cmd, client, organization, database.ProvisionerType(provisioner), resp.Hash, parameterFile)
job, _, err := createValidTemplateVersion(cmd, createValidTemplateVersionArgs{
Client: client,
Organization: organization,
Provisioner: database.ProvisionerType(provisioner),
FileHash: resp.Hash,
ParameterFile: parameterFile,
})
if err != nil {
return err
}
Expand All @@ -98,7 +104,6 @@ func templateCreate() *cobra.Command {
createReq := codersdk.CreateTemplateRequest{
Name: templateName,
VersionID: job.ID,
ParameterValues: parameters,
MaxTTLMillis: ptr.Ref(maxTTL.Milliseconds()),
MinAutostartIntervalMillis: ptr.Ref(minAutostartInterval.Milliseconds()),
}
Expand Down Expand Up @@ -133,14 +138,34 @@ func templateCreate() *cobra.Command {
return cmd
}

func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, organization codersdk.Organization, provisioner database.ProvisionerType, hash string, parameterFile string, parameters ...codersdk.CreateParameterRequest) (*codersdk.TemplateVersion, []codersdk.CreateParameterRequest, error) {
type createValidTemplateVersionArgs struct {
Client *codersdk.Client
Organization codersdk.Organization
Provisioner database.ProvisionerType
FileHash string
ParameterFile string
// Template is only required if updating a template's active version.
Template *codersdk.Template
// ReuseParams will attempt to reuse params from the Template field
// before prompting the user. Set to false to always prompt for param
// values.
ReuseParams bool
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 making this opt-in

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I plan to add some kind of --always-prompt flag if you want to change the params.

}

func createValidTemplateVersion(cmd *cobra.Command, args createValidTemplateVersionArgs, parameters ...codersdk.CreateParameterRequest) (*codersdk.TemplateVersion, []codersdk.CreateParameterRequest, error) {
Copy link
Member

@johnstcn johnstcn Jun 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah we're there now :D (args struct)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really want to try refactoring this function. It's growing limbs and becoming quite large lol.

"Get it working" was my first step...

before := time.Now()
version, err := client.CreateTemplateVersion(cmd.Context(), organization.ID, codersdk.CreateTemplateVersionRequest{
client := args.Client

req := codersdk.CreateTemplateVersionRequest{
StorageMethod: codersdk.ProvisionerStorageMethodFile,
StorageSource: hash,
Provisioner: codersdk.ProvisionerType(provisioner),
StorageSource: args.FileHash,
Provisioner: codersdk.ProvisionerType(args.Provisioner),
ParameterValues: parameters,
})
}
if args.Template != nil {
req.TemplateID = args.Template.ID
}
version, err := client.CreateTemplateVersion(cmd.Context(), args.Organization.ID, req)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -175,11 +200,32 @@ func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, org
return nil, nil, err
}

// lastParameterValues are pulled from the current active template version if
// templateID is provided. This allows pulling params from the last
// version instead of prompting if we are updating template versions.
lastParameterValues := make(map[string]codersdk.Parameter)
if args.ReuseParams && args.Template != nil {
activeVersion, err := client.TemplateVersion(cmd.Context(), args.Template.ActiveVersionID)
if err != nil {
return nil, nil, xerrors.Errorf("Fetch current active template version: %w", err)
}

// We don't want to compute the params, we only want to copy from this scope
values, err := client.Parameters(cmd.Context(), codersdk.ParameterImportJob, activeVersion.Job.ID)
if err != nil {
return nil, nil, xerrors.Errorf("Fetch previous version parameters: %w", err)
}
for _, value := range values {
lastParameterValues[value.Name] = value
}
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question (non-blocking): is the "currently active" template version always guaranteed to be the "last" one?
Either way, I think this is probably the expected behaviour; you want to just re-use what you already have.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No it's not always the last one. This is actually intentional, as if you upload a template_version that fails, it won't become the "active" template, but it will be the "last" template.

So the "active" template is usually the last working template version

if provisionerd.IsMissingParameterError(version.Job.Error) {
valuesBySchemaID := map[string]codersdk.TemplateVersionParameter{}
for _, parameterValue := range parameterValues {
valuesBySchemaID[parameterValue.SchemaID.String()] = parameterValue
}

sort.Slice(parameterSchemas, func(i, j int) bool {
return parameterSchemas[i].Name < parameterSchemas[j].Name
})
Expand All @@ -195,14 +241,22 @@ func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, org

// parameterMapFromFile can be nil if parameter file is not specified
var parameterMapFromFile map[string]string
if parameterFile != "" {
if args.ParameterFile != "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should remove the ParameterFile in favor of a --var=asd=asd approach. Separate issue, but I think it conflates some of this logic.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file logic needs to be looked at for sure. I kept it as is for now.

_, _ = fmt.Fprintln(cmd.OutOrStdout(), cliui.Styles.Paragraph.Render("Attempting to read the variables from the parameter file.")+"\r\n")
parameterMapFromFile, err = createParameterMapFromFile(parameterFile)
parameterMapFromFile, err = createParameterMapFromFile(args.ParameterFile)
if err != nil {
return nil, nil, err
}
}
for _, parameterSchema := range missingSchemas {
// If the value is in the file, skip trying to reuse the param
_, fileOk := parameterMapFromFile[parameterSchema.Name]
if inherit, ok := lastParameterValues[parameterSchema.Name]; ok && !fileOk {
parameters = append(parameters, codersdk.CreateParameterRequest{
CopyFromParameter: inherit.ID,
})
continue
}
parameterValue, err := getParameterValueFromMapOrInput(cmd, parameterMapFromFile, parameterSchema)
if err != nil {
return nil, nil, err
Expand All @@ -218,7 +272,7 @@ func createValidTemplateVersion(cmd *cobra.Command, client *codersdk.Client, org

// This recursion is only 1 level deep in practice.
// The first pass populates the missing parameters, so it does not enter this `if` block again.
return createValidTemplateVersion(cmd, client, organization, provisioner, hash, parameterFile, parameters...)
return createValidTemplateVersion(cmd, args, parameters...)
}

if version.Job.Status != codersdk.ProvisionerJobSucceeded {
Expand Down
47 changes: 23 additions & 24 deletions cli/templateupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import (
"golang.org/x/xerrors"

"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/provisionersdk"
)

func templateUpdate() *cobra.Command {
var (
directory string
provisioner string
directory string
provisioner string
parameterFile string
)

cmd := &cobra.Command{
Expand Down Expand Up @@ -64,42 +66,38 @@ func templateUpdate() *cobra.Command {
}
spin.Stop()

before := time.Now()
templateVersion, err := client.CreateTemplateVersion(cmd.Context(), organization.ID, codersdk.CreateTemplateVersionRequest{
TemplateID: template.ID,
StorageMethod: codersdk.ProvisionerStorageMethodFile,
StorageSource: resp.Hash,
Provisioner: codersdk.ProvisionerType(provisioner),
job, _, err := createValidTemplateVersion(cmd, createValidTemplateVersionArgs{
Client: client,
Organization: organization,
Provisioner: database.ProvisionerType(provisioner),
FileHash: resp.Hash,
ParameterFile: parameterFile,
Template: &template,
ReuseParams: true,
})
if err != nil {
return err
}
logs, err := client.TemplateVersionLogsAfter(cmd.Context(), templateVersion.ID, before)
if err != nil {
return err
}
for {
log, ok := <-logs
if !ok {
break
}
_, _ = fmt.Printf("%s (%s): %s\n", provisioner, log.Level, log.Output)

if job.Job.Status != codersdk.ProvisionerJobSucceeded {
return xerrors.Errorf("job failed: %s", job.Job.Status)
}
templateVersion, err = client.TemplateVersion(cmd.Context(), templateVersion.ID)

_, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: "Confirm create?",
IsConfirm: true,
})
if err != nil {
return err
}

if templateVersion.Job.Status != codersdk.ProvisionerJobSucceeded {
return xerrors.Errorf("job failed: %s", templateVersion.Job.Error)
}

err = client.UpdateActiveTemplateVersion(cmd.Context(), template.ID, codersdk.UpdateActiveTemplateVersion{
ID: templateVersion.ID,
ID: job.ID,
})
if err != nil {
return err
}

_, _ = fmt.Printf("Updated version!\n")
return nil
},
Expand All @@ -108,6 +106,7 @@ func templateUpdate() *cobra.Command {
currentDirectory, _ := os.Getwd()
cmd.Flags().StringVarP(&directory, "directory", "d", currentDirectory, "Specify the directory to create from")
cmd.Flags().StringVarP(&provisioner, "test.provisioner", "", "terraform", "Customize the provisioner backend")
cmd.Flags().StringVarP(&parameterFile, "parameter-file", "", "", "Specify a file path with parameter values.")
cliui.AllowSkipPrompt(cmd)
// This is for testing!
err := cmd.Flags().MarkHidden("test.provisioner")
Expand Down
42 changes: 37 additions & 5 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ func (q *fakeQuerier) AcquireProvisionerJob(_ context.Context, arg database.Acqu
return database.ProvisionerJob{}, sql.ErrNoRows
}

func (q *fakeQuerier) ParameterValue(_ context.Context, id uuid.UUID) (database.ParameterValue, error) {
q.mutex.Lock()
defer q.mutex.Unlock()

for _, parameterValue := range q.parameterValues {
if parameterValue.ID.String() != id.String() {
continue
}
return parameterValue, nil
}
return database.ParameterValue{}, sql.ErrNoRows
}

func (q *fakeQuerier) DeleteParameterValueByID(_ context.Context, id uuid.UUID) error {
q.mutex.Lock()
defer q.mutex.Unlock()
Expand Down Expand Up @@ -703,17 +716,27 @@ func (q *fakeQuerier) GetOrganizationsByUserID(_ context.Context, userID uuid.UU
return organizations, nil
}

func (q *fakeQuerier) GetParameterValuesByScope(_ context.Context, arg database.GetParameterValuesByScopeParams) ([]database.ParameterValue, error) {
func (q *fakeQuerier) ParameterValues(_ context.Context, arg database.ParameterValuesParams) ([]database.ParameterValue, error) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made 1 query with filter options rather than adding new specific queries

q.mutex.RLock()
defer q.mutex.RUnlock()

parameterValues := make([]database.ParameterValue, 0)
for _, parameterValue := range q.parameterValues {
if parameterValue.Scope != arg.Scope {
continue
if len(arg.Scopes) > 0 {
if !contains(arg.Scopes, parameterValue.Scope) {
continue
}
}
if parameterValue.ScopeID != arg.ScopeID {
continue
if len(arg.ScopeIds) > 0 {
if !contains(arg.ScopeIds, parameterValue.ScopeID) {
continue
}
}

if len(arg.Ids) > 0 {
if !contains(arg.Ids, parameterValue.ID) {
continue
}
}
parameterValues = append(parameterValues, parameterValue)
}
Expand Down Expand Up @@ -1966,3 +1989,12 @@ func (q *fakeQuerier) InsertAuditLog(_ context.Context, arg database.InsertAudit

return alog, nil
}

func contains[T comparable](haystack []T, needle T) bool {
for _, hay := range haystack {
if needle == hay {
return true
}
}
return false
}
3 changes: 2 additions & 1 deletion coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading