Skip to content

feat: reinitialize agents when a prebuilt workspace is claimed #17475

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

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
c09c9b9
WIP: agent reinitialization
SasSwart Apr 21, 2025
476fe71
fix assignment to nil map
SasSwart Apr 21, 2025
8c8bca6
fix: ensure prebuilt workspace agent tokens are reused when a prebuil…
SasSwart Apr 23, 2025
7ce4eea
test agent reinitialization
SasSwart Apr 24, 2025
52ac64e
remove defunct metric
SasSwart Apr 24, 2025
362db7c
Remove todo
SasSwart Apr 25, 2025
dcc7379
test that we trigger workspace agent reinitialization under the right…
SasSwart Apr 28, 2025
ff66b3f
slight improvements to a test
SasSwart Apr 28, 2025
efff5d9
review notes to improve legibility
SasSwart Apr 28, 2025
cebd5db
add an integration test for prebuilt workspace agent reinitialization
SasSwart Apr 29, 2025
2679138
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart Apr 29, 2025
9feebef
enable the premium license in a prebuilds integration test
SasSwart Apr 29, 2025
b117b5c
encapsulate WaitForReinitLoop for easier testing
SasSwart Apr 30, 2025
a22b414
introduce unit testable abstraction layers
SasSwart Apr 30, 2025
9bbd2c7
test workspace claim pubsub
SasSwart May 1, 2025
5804201
add tests for agent reinitialization
SasSwart May 1, 2025
7e8dcee
review notes
SasSwart May 1, 2025
725f97b
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 1, 2025
a9b1567
make fmt lint
SasSwart May 1, 2025
21ee970
remove go mod replace
SasSwart May 1, 2025
e54d7e7
remove defunct logging
SasSwart May 1, 2025
2799858
update dependency on terraform-provider-coder
SasSwart May 2, 2025
1d93003
update dependency on terraform-provider-coder
SasSwart May 2, 2025
763fc12
go mod tidy
SasSwart May 2, 2025
0f879c7
make -B gen
SasSwart May 2, 2025
61784c9
dont require ids to InsertPresetParameters
SasSwart May 2, 2025
604eb27
dont require ids to InsertPresetParameters
SasSwart May 2, 2025
bf4d2cf
fix: set the running agent token
dannykopping May 2, 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
Prev Previous commit
Next Next commit
fix: ensure prebuilt workspace agent tokens are reused when a prebuil…
…d agent reinitializes
  • Loading branch information
SasSwart committed Apr 25, 2025
commit 8c8bca6886aa6731af799012f5ed89539cc2553e
75 changes: 64 additions & 11 deletions provisioner/terraform/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,17 +261,6 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l
e.mut.Lock()
defer e.mut.Unlock()

// TODO: defunct?
// var isPrebuild bool
// for _, v := range env {
// if envName(v) == provider.IsPrebuildEnvironmentVariable() && envVar(v) == "true" {
// isPrebuild = true
// break
// }
// }

// _ = isPrebuild

planfilePath := getPlanFilePath(e.workdir)
args := []string{
"plan",
Expand Down Expand Up @@ -341,6 +330,68 @@ func onlyDataResources(sm tfjson.StateModule) tfjson.StateModule {
return filtered
}

func (e *executor) logResourceReplacements(ctx context.Context, plan *tfjson.Plan) {
if plan == nil {
return
}

if len(plan.ResourceChanges) == 0 {
return
}
var (
count int
replacements = make(map[string][]string, 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
}

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)
}

count++
}

if count > 0 {
e.server.logger.Warn(ctx, "plan introduces resource changes", slog.F("count", count))
for n, p := range replacements {
e.server.logger.Warn(ctx, "resource will be replaced!", slog.F("name", n), slog.F("replacement_paths", strings.Join(p, ",")))
}
}
}

// planResources must only be called while the lock is held.
func (e *executor) planResources(ctx, killCtx context.Context, planfilePath string) (*State, json.RawMessage, error) {
ctx, span := e.server.startTrace(ctx, tracing.FuncName())
Expand All @@ -351,6 +402,8 @@ func (e *executor) planResources(ctx, killCtx context.Context, planfilePath stri
return nil, nil, xerrors.Errorf("show terraform plan file: %w", err)
}

e.logResourceReplacements(ctx, plan)

rawGraph, err := e.graph(ctx, killCtx)
if err != nil {
return nil, nil, xerrors.Errorf("graph: %w", err)
Expand Down
19 changes: 7 additions & 12 deletions provisioner/terraform/provision.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,21 +272,16 @@ func provisionEnv(
)
if metadata.GetIsPrebuild() {
env = append(env, provider.IsPrebuildEnvironmentVariable()+"=true")
}
tokens := metadata.GetRunningAgentAuthTokens()
if len(tokens) == 1 {
env = append(env, provider.RunningAgentTokenEnvironmentVariable("")+"="+tokens[0].Token)
} else {
// TODO: provide an agentID to these functions so that we provide the right token
// for single agent support, we use the zero value "" as the agentID
// TODO: looks like we only provide agent tokens for reinit if metadata.GetIsPrebuild() is false
// check this for consistency wherever else we use the isPrebuild attribute from the Proto and where we use the env derived from it.
const singleAgentID = ""
tokens := metadata.GetRunningAgentAuthTokens()
var token string
for _, t := range tokens {
if t.AgentId == singleAgentID {
token = t.Token
break
}
// If there are multiple agents, provide all the tokens to terraform so that it can
// choose the correct one for each agent ID.
env = append(env, provider.RunningAgentTokenEnvironmentVariable(t.AgentId)+"="+t.Token)
}
env = append(env, provider.RunningAgentTokenEnvironmentVariable(singleAgentID)+"="+token)
}
for key, value := range provisionersdk.AgentScriptEnv() {
env = append(env, key+"="+value)
Expand Down