Skip to content

fix: make template push a superset of template create #11299

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

Closed
wants to merge 19 commits into from
Next Next commit
fix: make template push a superset of template create
  • Loading branch information
f0ssel committed Jan 2, 2024
commit 7ce08a14c121425eedeb222867aa2f1c9fc1ec22
73 changes: 73 additions & 0 deletions cli/templatecreate.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"context"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -46,6 +47,7 @@ func (r *RootCmd) templateCreate() *clibase.Cmd {
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
<<<<<<< HEAD
isTemplateSchedulingOptionsSet := failureTTL != 0 || dormancyThreshold != 0 || dormancyAutoDeletion != 0 || maxTTL != 0

if isTemplateSchedulingOptionsSet || requireActiveVersion {
Expand Down Expand Up @@ -79,6 +81,19 @@ func (r *RootCmd) templateCreate() *clibase.Cmd {
return xerrors.Errorf("your license is not entitled to use enterprise access control, so you cannot set --require-active-version")
}
}
=======
err := handleEntitlements(inv.Context(), handleEntitlementsArgs{
client: client,
requireActiveVersion: requireActiveVersion,
defaultTTL: defaultTTL,
failureTTL: failureTTL,
dormancyThreshold: dormancyThreshold,
dormancyAutoDeletion: dormancyAutoDeletion,
maxTTL: maxTTL,
})
if err != nil {
return err
>>>>>>> 7b0afe8e9 (fix: make template push a superset of template create)
}

organization, err := CurrentOrganization(inv, client)
Expand Down Expand Up @@ -357,3 +372,61 @@ func ParseProvisionerTags(rawTags []string) (map[string]string, error) {
}
return tags, nil
}

type handleEntitlementsArgs struct {
client *codersdk.Client
requireActiveVersion bool
defaultTTL time.Duration
failureTTL time.Duration
dormancyThreshold time.Duration
dormancyAutoDeletion time.Duration
maxTTL time.Duration
}

func handleEntitlements(ctx context.Context, args handleEntitlementsArgs) error {
isTemplateSchedulingOptionsSet := args.failureTTL != 0 || args.dormancyThreshold != 0 || args.dormancyAutoDeletion != 0 || args.maxTTL != 0

if isTemplateSchedulingOptionsSet || args.requireActiveVersion {
if args.failureTTL != 0 || args.dormancyThreshold != 0 || args.dormancyAutoDeletion != 0 {
// This call can be removed when workspace_actions is no longer experimental
experiments, exErr := args.client.Experiments(ctx)
if exErr != nil {
return xerrors.Errorf("get experiments: %w", exErr)
}

if !experiments.Enabled(codersdk.ExperimentWorkspaceActions) {
Copy link
Member

Choose a reason for hiding this comment

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

Aside: I've noticed us call this "WorkspaceActions" and "WorkspaceCleanup" in different places. E.g. here. @sreya can we standardize on one? Workspace Cleanup makes more sense to me.

return xerrors.Errorf("--failure-ttl, --dormancy-threshold, and --dormancy-auto-deletion are experimental features. Use the workspace_actions CODER_EXPERIMENTS flag to set these configuration values.")
}
}

entitlements, err := args.client.Entitlements(ctx)
if cerr, ok := codersdk.AsError(err); ok && cerr.StatusCode() == http.StatusNotFound {
return xerrors.Errorf("your deployment appears to be an AGPL deployment, so you cannot set enterprise-only flags")
} else if err != nil {
return xerrors.Errorf("get entitlements: %w", err)
}

if isTemplateSchedulingOptionsSet {
if !entitlements.Features[codersdk.FeatureAdvancedTemplateScheduling].Enabled {
return xerrors.Errorf("your license is not entitled to use advanced template scheduling, so you cannot set --failure-ttl, --inactivity-ttl, or --max-ttl")
}
}

if args.requireActiveVersion {
if !entitlements.Features[codersdk.FeatureAccessControl].Enabled {
return xerrors.Errorf("your license is not entitled to use enterprise access control, so you cannot set --require-active-version")
}

experiments, exErr := args.client.Experiments(ctx)
if exErr != nil {
return xerrors.Errorf("get experiments: %w", exErr)
}

if !experiments.Enabled(codersdk.ExperimentTemplateUpdatePolicies) {
return xerrors.Errorf("--require-active-version is an experimental feature, contact an administrator to enable the 'template_update_policies' experiment on your Coder server")
}
}
}

return nil
}
124 changes: 109 additions & 15 deletions cli/templatepush.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package cli

import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"

"github.com/briandowns/spinner"
"golang.org/x/xerrors"
Expand Down Expand Up @@ -158,14 +161,20 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
var (
versionName string
provisioner string
workdir string
variablesFile string
commandLineVariables []string
alwaysPrompt bool
provisionerTags []string
uploadFlags templateUploadFlags
activate bool
create bool

requireActiveVersion bool
disableEveryone bool
defaultTTL time.Duration
failureTTL time.Duration
dormancyThreshold time.Duration
dormancyAutoDeletion time.Duration
maxTTL time.Duration
)
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Expand All @@ -176,7 +185,18 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
uploadFlags.setWorkdir(workdir)
err := handleEntitlements(inv.Context(), handleEntitlementsArgs{
client: client,
requireActiveVersion: requireActiveVersion,
defaultTTL: defaultTTL,
failureTTL: failureTTL,
dormancyThreshold: dormancyThreshold,
dormancyAutoDeletion: dormancyAutoDeletion,
maxTTL: maxTTL,
})
if err != nil {
return err
}

organization, err := CurrentOrganization(inv, client)
if err != nil {
Expand All @@ -188,10 +208,15 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
return err
}

if utf8.RuneCountInString(name) > 31 {
Copy link
Member

Choose a reason for hiding this comment

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

Nit:

Suggested change
if utf8.RuneCountInString(name) > 31 {
if utf8.RuneCountInString(name) >= 32 {

less cognitive overhead to read the if statement and comment this way

return xerrors.Errorf("Template name must be less than 32 characters")
}

var createTemplate bool
template, err := client.TemplateByName(inv.Context(), organization.ID, name)
if err != nil {
if !create {
var apiError *codersdk.Error
if errors.As(err, &apiError) && apiError.StatusCode() != http.StatusNotFound {
return err
}
createTemplate = true
Expand Down Expand Up @@ -268,6 +293,48 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
}
}

editTemplate := requireActiveVersion ||
disableEveryone ||
defaultTTL != 0 ||
failureTTL != 0 ||
dormancyThreshold != 0 ||
dormancyAutoDeletion != 0 ||
maxTTL != 0
if editTemplate {
if defaultTTL == 0 {
defaultTTL = time.Duration(template.DefaultTTLMillis) * time.Millisecond
}
if failureTTL == 0 {
failureTTL = time.Duration(template.FailureTTLMillis) * time.Millisecond
}
if dormancyThreshold == 0 {
dormancyThreshold = time.Duration(template.TimeTilDormantMillis) * time.Millisecond
}
if dormancyAutoDeletion == 0 {
dormancyAutoDeletion = time.Duration(template.TimeTilDormantAutoDeleteMillis) * time.Millisecond
}
if maxTTL == 0 {
maxTTL = time.Duration(template.MaxTTLMillis) * time.Millisecond
}
req := codersdk.UpdateTemplateMeta{
RequireActiveVersion: requireActiveVersion,
DisableEveryone: disableEveryone,
DefaultTTLMillis: defaultTTL.Milliseconds(),
FailureTTLMillis: failureTTL.Milliseconds(),
TimeTilDormantMillis: dormancyThreshold.Milliseconds(),
TimeTilDormantAutoDeleteMillis: dormancyAutoDeletion.Milliseconds(),
MaxTTLMillis: maxTTL.Milliseconds(),
}

_, err = client.UpdateTemplateMeta(inv.Context(), template.ID, req)
if err != nil {
return xerrors.Errorf("update template metadata: %w", err)
}
if err != nil {
return err
}
}

_, _ = fmt.Fprintf(inv.Stdout, "Updated version at %s!\n", pretty.Sprint(cliui.DefaultStyles.DateTimeStamp, time.Now().Format(time.Stamp)))
return nil
},
Expand All @@ -282,14 +349,6 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
// This is for testing!
Hidden: true,
},
{
Flag: "test.workdir",
Description: "Customize the working directory.",
Default: "",
Value: clibase.StringOf(&workdir),
// This is for testing!
Hidden: true,
},
{
Flag: "variables-file",
Description: "Specify a file path with values for Terraform-managed variables.",
Expand Down Expand Up @@ -327,10 +386,45 @@ func (r *RootCmd) templatePush() *clibase.Cmd {
Value: clibase.BoolOf(&activate),
},
{
Flag: "create",
Description: "Create the template if it does not exist.",
Flag: "require-active-version",
Description: "Requires workspace builds to use the active template version. This setting does not apply to template admins. This is an enterprise-only feature.",
Value: clibase.BoolOf(&requireActiveVersion),
Default: "false",
Value: clibase.BoolOf(&create),
},
{
Flag: "default-ttl",
Description: "Specify a default TTL for workspaces created from this template. It is the default time before shutdown - workspaces created from this template default to this value. Maps to \"Default autostop\" in the UI.",
Default: "24h",
Value: clibase.DurationOf(&defaultTTL),
},
{
Flag: "failure-ttl",
Description: "Specify a failure TTL for workspaces created from this template. It is the amount of time after a failed \"start\" build before coder automatically schedules a \"stop\" build to cleanup.This licensed feature's default is 0h (off). Maps to \"Failure cleanup\"in the UI.",
Default: "0h",
Value: clibase.DurationOf(&failureTTL),
},
{
Flag: "dormancy-threshold",
Description: "Specify a duration workspaces may be inactive prior to being moved to the dormant state. This licensed feature's default is 0h (off). Maps to \"Dormancy threshold\" in the UI.",
Default: "0h",
Value: clibase.DurationOf(&dormancyThreshold),
},
{
Flag: "dormancy-auto-deletion",
Description: "Specify a duration workspaces may be in the dormant state prior to being deleted. This licensed feature's default is 0h (off). Maps to \"Dormancy Auto-Deletion\" in the UI.",
Default: "0h",
Value: clibase.DurationOf(&dormancyAutoDeletion),
},
{
Flag: "max-ttl",
Description: "Edit the template maximum time before shutdown - workspaces created from this template must shutdown within the given duration after starting. This is an enterprise-only feature.",
Value: clibase.DurationOf(&maxTTL),
},
{
Flag: "private",
Description: "Disable the default behavior of granting template access to the 'everyone' group. " +
"The template permissions must be updated to allow non-admin users to use this template.",
Value: clibase.BoolOf(&disableEveryone),
},
cliui.SkipPromptOption(),
}
Expand Down