Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: implement dynamic parameter validation#18482

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
Emyrk wants to merge2 commits intostevenmasley/parameters_to_preview
base:stevenmasley/parameters_to_preview
Choose a base branch
Loading
fromstevenmasley/dynamic_validate
Draft
Show file tree
Hide file tree
Changes fromall 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
2 changes: 1 addition & 1 deletioncli/server.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1125,7 +1125,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
autobuildTicker := time.NewTicker(vals.AutobuildPollInterval.Value())
defer autobuildTicker.Stop()
autobuildExecutor := autobuild.NewExecutor(
ctx, options.Database, options.Pubsub, options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments)
ctx, options.Database, options.Pubsub,coderAPI.FileCache,options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments)
autobuildExecutor.Run()

jobReaperTicker := time.NewTicker(vals.JobReaperDetectorInterval.Value())
Expand Down
7 changes: 5 additions & 2 deletionscoderd/autobuild/lifecycle_executor.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@ import (
"golang.org/x/xerrors"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/files"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
Expand All@@ -35,6 +36,7 @@ type Executor struct {
ctx context.Context
db database.Store
ps pubsub.Pubsub
fileCache *files.Cache
templateScheduleStore *atomic.Pointer[schedule.TemplateScheduleStore]
accessControlStore *atomic.Pointer[dbauthz.AccessControlStore]
auditor *atomic.Pointer[audit.Auditor]
Expand All@@ -61,13 +63,14 @@ type Stats struct {
}

// New returns a new wsactions executor.
func NewExecutor(ctx context.Context, db database.Store, ps pubsub.Pubsub, reg prometheus.Registerer, tss *atomic.Pointer[schedule.TemplateScheduleStore], auditor *atomic.Pointer[audit.Auditor], acs *atomic.Pointer[dbauthz.AccessControlStore], log slog.Logger, tick <-chan time.Time, enqueuer notifications.Enqueuer, exp codersdk.Experiments) *Executor {
func NewExecutor(ctx context.Context, db database.Store, ps pubsub.Pubsub,fc *files.Cache,reg prometheus.Registerer, tss *atomic.Pointer[schedule.TemplateScheduleStore], auditor *atomic.Pointer[audit.Auditor], acs *atomic.Pointer[dbauthz.AccessControlStore], log slog.Logger, tick <-chan time.Time, enqueuer notifications.Enqueuer, exp codersdk.Experiments) *Executor {
factory := promauto.With(reg)
le := &Executor{
//nolint:gocritic // Autostart has a limited set of permissions.
ctx: dbauthz.AsAutostart(ctx),
db: db,
ps: ps,
fileCache: fc,
templateScheduleStore: tss,
tick: tick,
log: log.Named("autobuild"),
Expand DownExpand Up@@ -276,7 +279,7 @@ func (e *Executor) runOnce(t time.Time) Stats {
}
}

nextBuild, job, _, err = builder.Build(e.ctx, tx, nil, audit.WorkspaceBuildBaggage{IP: "127.0.0.1"})
nextBuild, job, _, err = builder.Build(e.ctx, tx,e.fileCache,nil, audit.WorkspaceBuildBaggage{IP: "127.0.0.1"})
if err != nil {
return xerrors.Errorf("build workspace with transition %q: %w", nextTransition, err)
}
Expand Down
2 changes: 2 additions & 0 deletionscoderd/coderdtest/coderdtest.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,6 +52,7 @@ import (
"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/files"
"github.com/coder/quartz"

"github.com/coder/coder/v2/coderd"
Expand DownExpand Up@@ -359,6 +360,7 @@ func NewOptions(t testing.TB, options *Options) (func(http.Handler), context.Can
ctx,
options.Database,
options.Pubsub,
files.NewFromStore(options.Database, prometheus.NewRegistry(), options.Authorizer),
prometheus.NewRegistry(),
&templateScheduleStore,
&auditor,
Expand Down
4 changes: 2 additions & 2 deletionscoderd/dynamicparameters/render.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,7 +50,7 @@ type loader struct {
// Prepare is the entrypoint for this package. It loads the necessary objects &
// files from the database and returns a Renderer that can be used to render the
// template version's parameters.
func Prepare(ctx context.Context, db database.Store, cache*files.Cache, versionID uuid.UUID, options ...func(r *loader)) (Renderer, error) {
func Prepare(ctx context.Context, db database.Store, cache files.FileAcquirer, versionID uuid.UUID, options ...func(r *loader)) (Renderer, error) {
l := &loader{
templateVersionID: versionID,
}
Expand DownExpand Up@@ -138,7 +138,7 @@ func (r *loader) loadData(ctx context.Context, db database.Store) error {
// Static parameter rendering is required to support older template versions that
// do not have the database state to support dynamic parameters. A constant
// warning will be displayed for these template versions.
func (r *loader) Renderer(ctx context.Context, db database.Store, cache*files.Cache) (Renderer, error) {
func (r *loader) Renderer(ctx context.Context, db database.Store, cache files.FileAcquirer) (Renderer, error) {
err := r.loadData(ctx, db)
if err != nil {
return nil, xerrors.Errorf("load data: %w", err)
Expand Down
33 changes: 33 additions & 0 deletionscoderd/dynamicparameters/render_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
package dynamicparameters

Check failure on line 1 in coderd/dynamicparameters/render_test.go

View workflow job for this annotation

GitHub Actions/ lint

package should be `dynamicparameters_test` instead of `dynamicparameters` (testpackage)

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestProvisionerVersionSupportsDynamicParameters(t *testing.T) {
t.Parallel()

for v, dyn := range map[string]bool{
"": false,
"na": false,
"0.0": false,
"0.10": false,
"1.4": false,
"1.5": false,
"1.6": true,
"1.7": true,
"1.8": true,
"2.0": true,
"2.17": true,
"4.0": true,
} {
t.Run(v, func(t *testing.T) {
t.Parallel()

does := ProvisionerVersionSupportsDynamicParameters(v)
require.Equal(t, dyn, does)
})
}
}
162 changes: 162 additions & 0 deletionscoderd/dynamicparameters/resolver.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
package dynamicparameters

import (
"context"
"fmt"

"github.com/google/uuid"
"github.com/hashicorp/hcl/v2"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
)

type ParameterResolver struct {
renderer Renderer

Check failure on line 16 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

field `renderer` is unused (unused)
firstBuild bool

Check failure on line 17 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

field `firstBuild` is unused (unused)
presetValues []database.TemplateVersionPresetParameter

Check failure on line 18 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

field `presetValues` is unused (unused)
previousValues []database.WorkspaceBuildParameter

Check failure on line 19 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

field `previousValues` is unused (unused)
buildValues []database.WorkspaceBuildParameter

Check failure on line 20 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

field `buildValues` is unused (unused)
}

type parameterValueSource int

const (
sourcePrevious parameterValueSource = iota
sourceBuild
sourcePreset
)

type parameterValue struct {
Value string
Source parameterValueSource
}

func ResolveParameters(

Check failure on line 36 in coderd/dynamicparameters/resolver.go

View workflow job for this annotation

GitHub Actions/ lint

flag-parameter: parameter 'firstBuild' seems to be a control flag, avoid control coupling (revive)
ctx context.Context,
ownerID uuid.UUID,
renderer Renderer,
firstBuild bool,
previousValues []database.WorkspaceBuildParameter,
buildValues []codersdk.WorkspaceBuildParameter,
presetValues []database.TemplateVersionPresetParameter,
) (map[string]string, hcl.Diagnostics) {
previousValuesMap := slice.ToMap(previousValues, func(p database.WorkspaceBuildParameter) (string, string) {
return p.Value, p.Value
})

// Start with previous
values := parameterValueMap(slice.ToMap(previousValues, func(p database.WorkspaceBuildParameter) (string, parameterValue) {
return p.Name, parameterValue{Source: sourcePrevious, Value: p.Value}
}))

// Add build values
for _, buildValue := range buildValues {
if _, ok := values[buildValue.Name]; !ok {
values[buildValue.Name] = parameterValue{Source: sourceBuild, Value: buildValue.Value}
}
}

// Add preset values
for _, preset := range presetValues {
if _, ok := values[preset.Name]; !ok {
values[preset.Name] = parameterValue{Source: sourcePreset, Value: preset.Value}
}
}

originalValues := make(map[string]parameterValue, len(values))
for name, value := range values {
// Store the original values for later use.
originalValues[name] = value
}

// Render the parameters using the values that were supplied to the previous build.
//
// This is how the form should look to the user on their workspace settings page.
// This is the original form truth that our validations should be based on going forward.
output, diags := renderer.Render(ctx, ownerID, values.ValuesMap())
if diags.HasErrors() {
// Top level diagnostics should break the build. Previous values (and new) should
// always be valid. If there is a case where this is not true, then this has to
// be changed to allow the build to continue with a different set of values.

return nil, diags
}

// The user's input now needs to be validated against the parameters.
// Mutability & Ephemeral parameters depend on sequential workspace builds.
//
// To enforce these, the user's input values are trimmed based on the
// mutability and ephemeral parameters defined in the template version.
// The output parameters
for _, parameter := range output.Parameters {
// Ephemeral parameters should not be taken from the previous build.
// Remove their values from the input if they are sourced from the previous build.
if parameter.Ephemeral {
v := values[parameter.Name]
if v.Source == sourcePrevious {
delete(values, parameter.Name)
}
}

// Immutable parameters should also not be allowed to be changed from
// the previous build. Remove any values taken from the preset or
// new build params. This forces the value to be the same as it was before.
if !firstBuild && !parameter.Mutable {
delete(values, parameter.Name)
prev, ok := previousValuesMap[parameter.Name]
if ok {
values[parameter.Name] = parameterValue{
Value: prev,
Source: sourcePrevious,
}
}
}
}

// This is the final set of values that will be used. Any errors at this stage
// are fatal. Additional validation for immutability has to be done manually.
output, diags = renderer.Render(ctx, ownerID, values.ValuesMap())
if diags.HasErrors() {
return nil, diags
}

for _, parameter := range output.Parameters {
if !firstBuild && !parameter.Mutable {
if parameter.Value.AsString() != originalValues[parameter.Name].Value {
var src *hcl.Range
if parameter.Source != nil {
src = &parameter.Source.HCLBlock().TypeRange
}

// An immutable parameter was changed, which is not allowed.
// Add the failed diagnostic to the output.
diags = diags.Append(&hcl.Diagnostic{
Severity: 0,
Summary: "Immutable parameter changed",
Detail: fmt.Sprintf("Parameter %q is not mutable, so it can't be updated after creating a workspace.", parameter.Name),
Subject: src,
})
}
}
}

// TODO: Validate all parameter values.

// Return the values to be saved for the build.
// TODO: The previous code always returned parameter names and values, even if they were not set
// by the user. So this should loop over the parameters and return all of them.
// This catches things like if a default value changes, we keep the old value.
return values.ValuesMap(), diags
}

type parameterValueMap map[string]parameterValue

func (p parameterValueMap) ValuesMap() map[string]string {
values := make(map[string]string, len(p))
for name, paramValue := range p {
values[name] = paramValue.Value
}
return values
}
10 changes: 10 additions & 0 deletionscoderd/util/slice/slice.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -230,3 +230,13 @@ func Convert[F any, T any](a []F, f func(F) T) []T {
}
return tmp
}

func ToMap[T any, K comparable, V any](a []T, cnv func(t T) (K, V)) map[K]V {
m := make(map[K]V, len(a))

for i := range a {
k, v := cnv(a[i])
m[k] = v
}
return m
}
1 change: 1 addition & 0 deletionscoderd/workspacebuilds.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -391,6 +391,7 @@ func (api *API) postWorkspaceBuilds(rw http.ResponseWriter, r *http.Request) {
workspaceBuild, provisionerJob, provisionerDaemons, err = builder.Build(
ctx,
tx,
api.FileCache,
func(action policy.Action, object rbac.Objecter) bool {
// Special handling for prebuilt workspace deletion
if object.RBACObject().Type == rbac.ResourceWorkspace.Type && action == policy.ActionDelete {
Expand Down
1 change: 1 addition & 0 deletionscoderd/workspaces.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -724,6 +724,7 @@ func createWorkspace(
workspaceBuild, provisionerJob, provisionerDaemons, err = builder.Build(
ctx,
db,
api.FileCache,
func(action policy.Action, object rbac.Objecter) bool {
return api.Authorize(r, action, object)
},
Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp