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: track resource replacements when claiming a prebuilt workspace#17571

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

Merged
dannykopping merged 38 commits intomainfromdk/logreplacements
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from1 commit
Commits
Show all changes
38 commits
Select commitHold shift + click to select a range
b32923a
feat: log resource replacements
dannykoppingApr 25, 2025
0b0830f
feat: show terraform state drift diff in build logs
dannykoppingApr 25, 2025
256395a
feat: only highlight lines which mention replacement
dannykoppingApr 25, 2025
61ef61a
feat: notify template admins when prebuild claim results in resource …
dannykoppingApr 25, 2025
a66559f
chore: appease linter
dannykoppingApr 25, 2025
222892b
chore: fix notifications test
dannykoppingApr 25, 2025
f34e011
fix: don't panic
dannykoppingApr 28, 2025
5168c01
fix: renaming type
dannykoppingApr 28, 2025
41e5e0c
chore: updating migration numbers
dannykoppingMay 6, 2025
b29e8fa
chore: minor touch-ups
dannykoppingMay 6, 2025
b31ed5e
feat: add resource replacements metric
dannykoppingMay 7, 2025
adf98d2
feat: add resource replacement notification
dannykoppingMay 7, 2025
f24aef0
make lint; make fmt
dannykoppingMay 7, 2025
70f9a53
chore: adding tests
dannykoppingMay 8, 2025
1e8385d
feat: pass flag to terraform provider when prebuilt workspace claimed
dannykoppingMay 9, 2025
d0f00ce
chore: update provider, add test for is_prebuild_claim
dannykoppingMay 12, 2025
11a2c5a
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 12, 2025
ce63b24
Merge branch 'dk/is-prebuild-claim' of github.com:/coder/coder into d…
dannykoppingMay 12, 2025
d2c5d43
chore: replace GetTemplatePresetsByID with GetPresetByID
dannykoppingMay 12, 2025
22d82a4
chore: correcting docs link
dannykoppingMay 12, 2025
5209aae
Merge branch 'main' of github.com:/coder/coder into dk/logreplacement
dannykoppingMay 12, 2025
39ce658
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 12, 2025
ac5655f
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 12, 2025
82c3f58
chore: note provisioner API change
dannykoppingMay 12, 2025
7577a90
chore: fixups
dannykoppingMay 13, 2025
a893b79
chore: adding note about immutable resources
dannykoppingMay 13, 2025
d9c906a
chore: review feedback
dannykoppingMay 13, 2025
471198a
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 13, 2025
7d694e6
chore: merge conflicts
dannykoppingMay 13, 2025
6b7a8b7
chore: fix 'is not iterable' bullshit
dannykoppingMay 13, 2025
5df2cb3
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 14, 2025
6d1c3ea
chore: rename migrations
dannykoppingMay 14, 2025
5f62702
chore: set notifications manager before enterprise server initializes…
dannykoppingMay 14, 2025
f74d799
chore: completing refactor since https://github.com/coder/coder/pull/…
dannykoppingMay 14, 2025
971f65c
chore: remove unnecessary atomicity since map is protected by mutex a…
dannykoppingMay 14, 2025
bc362b0
chore: appeasing linter's Very Important Suggestion
dannykoppingMay 14, 2025
4fbd356
Merge branch 'main' of github.com:/coder/coder into dk/logreplacements
dannykoppingMay 14, 2025
b9eb8be
chore: remove old replacement logging
dannykoppingMay 14, 2025
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
NextNext commit
feat: log resource replacements
Signed-off-by: Danny Kopping <dannykopping@gmail.com>
  • Loading branch information
@dannykopping
dannykopping committedMay 8, 2025
commitb32923ad83151a04934d8e461162af1a9ba5630f
6 changes: 6 additions & 0 deletionscoderd/provisionerdserver/provisionerdserver.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -617,6 +617,11 @@ func (s *server) acquireProtoJob(ctx context.Context, job database.ProvisionerJo
}
}

var prebuildClaimedForUserID string
if input.PrebuildClaimedByUser != uuid.Nil {
prebuildClaimedForUserID = input.PrebuildClaimedByUser.String()
}

protoJob.Type = &proto.AcquiredJob_WorkspaceBuild_{
WorkspaceBuild: &proto.AcquiredJob_WorkspaceBuild{
WorkspaceBuildId: workspaceBuild.ID.String(),
Expand DownExpand Up@@ -646,6 +651,7 @@ func (s *server) acquireProtoJob(ctx context.Context, job database.ProvisionerJo
WorkspaceOwnerLoginType: string(owner.LoginType),
WorkspaceOwnerRbacRoles: ownerRbacRoles,
IsPrebuild: input.IsPrebuild,
PrebuildClaimForUserId: prebuildClaimedForUserID,
},
LogLevel: input.LogLevel,
},
Expand Down
31 changes: 23 additions & 8 deletionsprovisioner/terraform/executor.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,7 +258,7 @@ func getStateFilePath(workdir string) string {
}

// revive:disable-next-line:flag-parameter
func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr logSink,destroy bool) (*proto.PlanComplete, error) {
func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr logSink,metadata *proto.Metadata) (*proto.PlanComplete, error) {
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

This is the meat of the feature; everything else is just plumbing between system and user eyeball.

ctx, span := e.server.startTrace(ctx, tracing.FuncName())
defer span.End()

Expand All@@ -274,6 +274,7 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l
"-refresh=true",
"-out=" + planfilePath,
}
destroy := metadata.GetWorkspaceTransition() == proto.WorkspaceTransition_DESTROY
if destroy {
args = append(args, "-destroy")
}
Expand All@@ -299,14 +300,28 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l
graphTimings := newTimingAggregator(database.ProvisionerJobTimingStageGraph)
graphTimings.ingest(createGraphTimingsEvent(timingGraphStart))

state, plan, err := e.planResources(ctx, killCtx, planfilePath)
state, plan,replacements,err := e.planResources(ctx, killCtx, planfilePath)
if err != nil {
graphTimings.ingest(createGraphTimingsEvent(timingGraphErrored))
return nil, err
}

graphTimings.ingest(createGraphTimingsEvent(timingGraphComplete))

// When a prebuild claim attempt is made, log a warning if a resource is due to be replaced, since this will obviate
// the point of prebuilding if the expensive resource is replaced once claimed!
//
// Future enhancement: send a notification (probably just to the inbox) to inform both the claimant and the template
// admin that a replacement took place. The provisioner does not connect to the database, so it can't enqueue notifications.
isPrebuildClaimAttempt := !destroy && metadata.PrebuildClaimForUserId != ""
if count := len(replacements); count > 0 && isPrebuildClaimAttempt {
e.server.logger.Warn(ctx, "plan introduces resource changes", slog.F("count", count))
for n, p := range replacements {
// TODO: link to documentation for description and solution.
e.server.logger.Warn(ctx, "resource will be replaced, which may impact prebuilt workspace", slog.F("name", n), slog.F("replacement_paths", strings.Join(p, ",")))
}
}

return &proto.PlanComplete{
Parameters: state.Parameters,
Resources: state.Resources,
Expand DownExpand Up@@ -335,18 +350,18 @@ func onlyDataResources(sm tfjson.StateModule) tfjson.StateModule {
}

// planResources must only be called while the lock is held.
func (e *executor) planResources(ctx, killCtx context.Context, planfilePath string) (*State, json.RawMessage, error) {
func (e *executor) planResources(ctx, killCtx context.Context, planfilePath string) (*State, json.RawMessage,resourceReplacements,error) {
ctx, span := e.server.startTrace(ctx, tracing.FuncName())
defer span.End()

plan, err := e.showPlan(ctx, killCtx, planfilePath)
if err != nil {
return nil, nil, xerrors.Errorf("show terraform plan file: %w", err)
return nil, nil,nil,xerrors.Errorf("show terraform plan file: %w", err)
}

rawGraph, err := e.graph(ctx, killCtx)
if err != nil {
return nil, nil, xerrors.Errorf("graph: %w", err)
return nil, nil,nil,xerrors.Errorf("graph: %w", err)
}
modules := []*tfjson.StateModule{}
if plan.PriorState != nil {
Expand All@@ -364,15 +379,15 @@ func (e *executor) planResources(ctx, killCtx context.Context, planfilePath stri

state, err := ConvertState(ctx, modules, rawGraph, e.server.logger)
if err != nil {
return nil, nil, err
return nil, nil,nil,err
}

planJSON, err := json.Marshal(plan)
if err != nil {
return nil, nil, err
return nil, nil,nil,err
}

return state, planJSON, nil
return state, planJSON,findResourceReplacements(plan),nil
}

// showPlan must only be called while the lock is held.
Expand Down
5 changes: 1 addition & 4 deletionsprovisioner/terraform/provision.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -163,10 +163,7 @@ func (s *server) Plan(
return provisionersdk.PlanErrorf("plan vars: %s", err)
}

resp, err := e.plan(
ctx, killCtx, env, vars, sess,
request.Metadata.GetWorkspaceTransition() == proto.WorkspaceTransition_DESTROY,
)
resp, err := e.plan(ctx, killCtx, env, vars, sess, request.Metadata)
if err != nil {
return provisionersdk.PlanErrorf("%s", err.Error())
}
Expand Down
74 changes: 74 additions & 0 deletionsprovisioner/terraform/resource_replacements.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
package terraform

import (
"fmt"
"strings"

tfjson "github.com/hashicorp/terraform-json"
)

type resourceReplacements map[string][]string

// resourceReplacements finds all resources which would be replaced by the current plan, and the attribute paths which
// caused the replacement.
//
// NOTE: "replacement" in terraform terms means that a resource will have to be destroyed and replaced with a new resource
// since one of its immutable attributes was modified, which cannot be updated in-place.
func findResourceReplacements(plan *tfjson.Plan) resourceReplacements {
if plan == nil {
return nil
}

// No changes, no problem!
if len(plan.ResourceChanges) == 0 {
return nil
}

replacements := make(resourceReplacements, len(plan.ResourceChanges))

for _, ch := range plan.ResourceChanges {
// No change, no problem!
if ch.Change == nil {
continue
}

// No-op change, no problem!
if ch.Change.Actions.NoOp() {
continue
}

// No replacements, no problem!
if len(ch.Change.ReplacePaths) == 0 {
continue
}

// Replacing our resources, no problem!
if strings.Index(ch.Type, "coder_") == 0 {
continue
}

// Replacements found, problem!
for _, p := range ch.Change.ReplacePaths {
var path string
switch p := p.(type) {
case []interface{}:
segs := p
list := make([]string, 0, len(segs))
for _, s := range segs {
list = append(list, fmt.Sprintf("%v", s))
}
path = strings.Join(list, ".")
default:
path = fmt.Sprintf("%v", p)
}

replacements[ch.Address] = append(replacements[ch.Address], path)
}
}

if len(replacements) == 0 {
return nil
}

return replacements
}
172 changes: 172 additions & 0 deletionsprovisioner/terraform/resource_replacements_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
package terraform

import (
"testing"

tfjson "github.com/hashicorp/terraform-json"
"github.com/stretchr/testify/require"
)

func TestFindResourceReplacements(t *testing.T) {
cases := []struct {
name string
plan *tfjson.Plan
expected resourceReplacements
}{
{
name: "nil plan",
},
{
name: "no resource changes",
plan: &tfjson.Plan{},
},
{
name: "resource change with nil change",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
},
},
},
},
{
name: "no-op action",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionNoop},
},
},
},
},
},
{
name: "empty replace paths",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
},
},
},
},
},
{
name: "coder_* types are ignored",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Type: "coder_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"path1"},
},
},
},
},
},
{
name: "valid replacements - single path",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Type: "example_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"path1"},
},
},
},
},
expected: resourceReplacements{
"resource1": {"path1"},
},
},
{
name: "valid replacements - multiple paths",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Type: "example_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"path1", "path2"},
},
},
},
},
expected: resourceReplacements{
"resource1": {"path1", "path2"},
},
},
{
name: "complex replace path",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Type: "example_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{
[]interface{}{"path", "to", "key"},
},
},
},
},
},
expected: resourceReplacements{
"resource1": {"path.to.key"},
},
},
{
name: "multiple changes",
plan: &tfjson.Plan{
ResourceChanges: []*tfjson.ResourceChange{
{
Address: "resource1",
Type: "example_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"path1"},
},
},
{
Address: "resource2",
Type: "example_resource",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"path2", "path3"},
},
},
{
Address: "resource3",
Type: "coder_example",
Change: &tfjson.Change{
Actions: tfjson.Actions{tfjson.ActionDelete, tfjson.ActionCreate},
ReplacePaths: []interface{}{"ignored_path"},
},
},
},
},
expected: resourceReplacements{
"resource1": {"path1"},
"resource2": {"path2", "path3"},
},
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require.EqualValues(t, tc.expected, findResourceReplacements(tc.plan))
})
}
}
Loading

[8]ページ先頭

©2009-2026 Movatter.jp