Skip to content

Commit 0c75392

Browse files
committed
chore: pass through file locations more cleanly
1 parent cbc9d5d commit 0c75392

File tree

9 files changed

+298
-158
lines changed

9 files changed

+298
-158
lines changed

provisioner/echo/serve.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ func readResponses(sess *provisionersdk.Session, trans string, suffix string) ([
122122
for i := 0; ; i++ {
123123
paths := []string{
124124
// Try more specific path first, then fallback to generic.
125-
filepath.Join(sess.WorkDirectory, fmt.Sprintf("%d.%s.%s", i, trans, suffix)),
126-
filepath.Join(sess.WorkDirectory, fmt.Sprintf("%d.%s", i, suffix)),
125+
filepath.Join(sess.Files.WorkDirectory(), fmt.Sprintf("%d.%s.%s", i, trans, suffix)),
126+
filepath.Join(sess.Files.WorkDirectory(), fmt.Sprintf("%d.%s", i, suffix)),
127127
}
128128
for pathIndex, path := range paths {
129129
_, err := os.Stat(path)

provisioner/terraform/executor.go

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"io"
1111
"os"
1212
"os/exec"
13-
"path/filepath"
1413
"runtime"
1514
"strings"
1615
"sync"
@@ -22,6 +21,7 @@ import (
2221
"golang.org/x/xerrors"
2322

2423
"cdr.dev/slog"
24+
"github.com/coder/coder/v2/provisionersdk/x"
2525

2626
"github.com/coder/coder/v2/coderd/database"
2727
"github.com/coder/coder/v2/coderd/tracing"
@@ -41,7 +41,7 @@ type executor struct {
4141
// cachePath and workdir must not be used by multiple processes at once.
4242
cachePath string
4343
cliConfigPath string
44-
workdir string
44+
workdir x.TerraformDirectory
4545
// used to capture execution times at various stages
4646
timings *timingAggregator
4747
}
@@ -90,7 +90,7 @@ func (e *executor) execWriteOutput(ctx, killCtx context.Context, args, env []str
9090

9191
// #nosec
9292
cmd := exec.CommandContext(killCtx, e.binaryPath, args...)
93-
cmd.Dir = e.workdir
93+
cmd.Dir = e.workdir.WorkDirectory()
9494
if env == nil {
9595
// We don't want to passthrough host env when unset.
9696
env = []string{}
@@ -131,7 +131,7 @@ func (e *executor) execParseJSON(ctx, killCtx context.Context, args, env []strin
131131

132132
// #nosec
133133
cmd := exec.CommandContext(killCtx, e.binaryPath, args...)
134-
cmd.Dir = e.workdir
134+
cmd.Dir = e.workdir.WorkDirectory()
135135
cmd.Env = env
136136
out := &bytes.Buffer{}
137137
stdErr := &bytes.Buffer{}
@@ -225,7 +225,7 @@ func (e *executor) init(ctx, killCtx context.Context, logr logSink) error {
225225
defer e.mut.Unlock()
226226

227227
// Record lock file checksum before init
228-
lockFilePath := filepath.Join(e.workdir, ".terraform.lock.hcl")
228+
lockFilePath := e.workdir.TerraformLockFile()
229229
preInitChecksum := checksumFileCRC32(ctx, e.logger, lockFilePath)
230230

231231
outWriter, doneOut := e.provisionLogWriter(logr)
@@ -289,14 +289,6 @@ func checksumFileCRC32(ctx context.Context, logger slog.Logger, path string) uin
289289
return crc32.ChecksumIEEE(content)
290290
}
291291

292-
func getPlanFilePath(workdir string) string {
293-
return filepath.Join(workdir, "terraform.tfplan")
294-
}
295-
296-
func getStateFilePath(workdir string) string {
297-
return filepath.Join(workdir, "terraform.tfstate")
298-
}
299-
300292
// revive:disable-next-line:flag-parameter
301293
func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr logSink, req *proto.PlanRequest) (*proto.PlanComplete, error) {
302294
ctx, span := e.server.startTrace(ctx, tracing.FuncName())
@@ -307,7 +299,7 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l
307299

308300
metadata := req.Metadata
309301

310-
planfilePath := getPlanFilePath(e.workdir)
302+
planfilePath := e.workdir.PlanFilePath()
311303
args := []string{
312304
"plan",
313305
"-no-color",
@@ -359,7 +351,7 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l
359351
// a workspace build. This removes some added costs of sending the modules
360352
// payload back to coderd if coderd is just going to ignore it.
361353
if !req.OmitModuleFiles {
362-
moduleFiles, err = GetModulesArchive(os.DirFS(e.workdir))
354+
moduleFiles, err = GetModulesArchive(os.DirFS(e.workdir.WorkDirectory()))
363355
if err != nil {
364356
// TODO: we probably want to persist this error or make it louder eventually
365357
e.logger.Warn(ctx, "failed to archive terraform modules", slog.Error(err))
@@ -551,7 +543,7 @@ func (e *executor) graph(ctx, killCtx context.Context) (string, error) {
551543
var out strings.Builder
552544
cmd := exec.CommandContext(killCtx, e.binaryPath, args...) // #nosec
553545
cmd.Stdout = &out
554-
cmd.Dir = e.workdir
546+
cmd.Dir = e.workdir.WorkDirectory()
555547
cmd.Env = e.basicEnv()
556548

557549
e.server.logger.Debug(ctx, "executing terraform command graph",
@@ -588,7 +580,7 @@ func (e *executor) apply(
588580
"-auto-approve",
589581
"-input=false",
590582
"-json",
591-
getPlanFilePath(e.workdir),
583+
e.workdir.PlanFilePath(),
592584
}
593585

594586
outWriter, doneOut := e.provisionLogWriter(logr)
@@ -608,7 +600,7 @@ func (e *executor) apply(
608600
if err != nil {
609601
return nil, err
610602
}
611-
statefilePath := getStateFilePath(e.workdir)
603+
statefilePath := e.workdir.StateFilePath()
612604
stateContent, err := os.ReadFile(statefilePath)
613605
if err != nil {
614606
return nil, xerrors.Errorf("read statefile %q: %w", statefilePath, err)

provisioner/terraform/modules.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ import (
77
"io"
88
"io/fs"
99
"os"
10-
"path/filepath"
1110
"strings"
1211
"time"
1312

1413
"golang.org/x/xerrors"
1514

1615
"github.com/coder/coder/v2/coderd/util/xio"
1716
"github.com/coder/coder/v2/provisionersdk/proto"
17+
"github.com/coder/coder/v2/provisionersdk/x"
1818
)
1919

2020
const (
@@ -39,10 +39,6 @@ type modulesFile struct {
3939
Modules []*module `json:"Modules"`
4040
}
4141

42-
func getModulesFilePath(workdir string) string {
43-
return filepath.Join(workdir, ".terraform", "modules", "modules.json")
44-
}
45-
4642
func parseModulesFile(filePath string) ([]*proto.Module, error) {
4743
modules := &modulesFile{}
4844
data, err := os.ReadFile(filePath)
@@ -62,8 +58,8 @@ func parseModulesFile(filePath string) ([]*proto.Module, error) {
6258
// getModules returns the modules from the modules file if it exists.
6359
// It returns nil if the file does not exist.
6460
// Modules become available after terraform init.
65-
func getModules(workdir string) ([]*proto.Module, error) {
66-
filePath := getModulesFilePath(workdir)
61+
func getModules(workdir x.TerraformDirectory) ([]*proto.Module, error) {
62+
filePath := workdir.ModulesFilePath()
6763
if _, err := os.Stat(filePath); os.IsNotExist(err) {
6864
return nil, nil
6965
}
@@ -82,7 +78,7 @@ func getModules(workdir string) ([]*proto.Module, error) {
8278
return filteredModules, nil
8379
}
8480

85-
func GetModulesArchive(root fs.FS) ([]byte, error) {
81+
func GetModulesArchive(root fs.FS, files x.TerraformDirectory) ([]byte, error) {
8682
modulesFileContent, err := fs.ReadFile(root, ".terraform/modules/modules.json")
8783
if err != nil {
8884
if xerrors.Is(err, fs.ErrNotExist) {

provisioner/terraform/parse.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ func (s *server) Parse(sess *provisionersdk.Session, _ *proto.ParseRequest, _ <-
2525
defer span.End()
2626

2727
// Load the module and print any parse errors.
28-
parser, diags := tfparse.New(sess.WorkDirectory, tfparse.WithLogger(s.logger.Named("tfparse")))
28+
parser, diags := tfparse.New(sess.Files.WorkDirectory(), tfparse.WithLogger(s.logger.Named("tfparse")))
2929
if diags.HasErrors() {
30-
return provisionersdk.ParseErrorf("load module: %s", formatDiagnostics(sess.WorkDirectory, diags))
30+
return provisionersdk.ParseErrorf("load module: %s", formatDiagnostics(sess.Files.WorkDirectory(), diags))
3131
}
3232

3333
workspaceTags, _, err := parser.WorkspaceTags(ctx)

provisioner/terraform/provision.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ func (s *server) Plan(
7676
defer cancel()
7777
defer kill()
7878

79-
e := s.executor(sess.WorkDirectory, database.ProvisionerJobTimingStagePlan)
79+
e := s.executor(sess.Files, database.ProvisionerJobTimingStagePlan)
8080
if err := e.checkMinVersion(ctx); err != nil {
8181
return provisionersdk.PlanErrorf("%s", err.Error())
8282
}
@@ -92,7 +92,7 @@ func (s *server) Plan(
9292
return &proto.PlanComplete{}
9393
}
9494

95-
statefilePath := getStateFilePath(sess.WorkDirectory)
95+
statefilePath := sess.Files.StateFilePath()
9696
if len(sess.Config.State) > 0 {
9797
err := os.WriteFile(statefilePath, sess.Config.State, 0o600)
9898
if err != nil {
@@ -141,7 +141,7 @@ func (s *server) Plan(
141141
return provisionersdk.PlanErrorf("initialize terraform: %s", err)
142142
}
143143

144-
modules, err := getModules(sess.WorkDirectory)
144+
modules, err := getModules(sess.Files)
145145
if err != nil {
146146
// We allow getModules to fail, as the result is used only
147147
// for telemetry purposes now.
@@ -184,7 +184,7 @@ func (s *server) Apply(
184184
defer cancel()
185185
defer kill()
186186

187-
e := s.executor(sess.WorkDirectory, database.ProvisionerJobTimingStageApply)
187+
e := s.executor(sess.Files, database.ProvisionerJobTimingStageApply)
188188
if err := e.checkMinVersion(ctx); err != nil {
189189
return provisionersdk.ApplyErrorf("%s", err.Error())
190190
}
@@ -201,7 +201,7 @@ func (s *server) Apply(
201201
}
202202

203203
// Earlier in the session, Plan() will have written the state file and the plan file.
204-
statefilePath := getStateFilePath(sess.WorkDirectory)
204+
statefilePath := sess.Files.StateFilePath()
205205
env, err := provisionEnv(sess.Config, request.Metadata, nil, nil, nil)
206206
if err != nil {
207207
return provisionersdk.ApplyErrorf("provision env: %s", err)
@@ -348,7 +348,7 @@ func logTerraformEnvVars(sink logSink) {
348348
// shipped in v1.0.4. It will return the stacktraces of the provider, which will hopefully allow us
349349
// to figure out why it hasn't exited.
350350
func tryGettingCoderProviderStacktrace(sess *provisionersdk.Session) string {
351-
path := filepath.Clean(filepath.Join(sess.WorkDirectory, "../.coder/pprof"))
351+
path := filepath.Clean(filepath.Join(sess.Files.WorkDirectory(), "../.coder/pprof"))
352352
sess.Logger.Info(sess.Context(), "attempting to get stack traces", slog.F("path", path))
353353
c := http.Client{
354354
Transport: &http.Transport{

provisioner/terraform/serve.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"golang.org/x/xerrors"
1515

1616
"cdr.dev/slog"
17+
"github.com/coder/coder/v2/provisionersdk/x"
1718

1819
"github.com/coder/coder/v2/coderd/database"
1920
"github.com/coder/coder/v2/coderd/jobreaper"
@@ -160,7 +161,7 @@ func (s *server) startTrace(ctx context.Context, name string, opts ...trace.Span
160161
))...)
161162
}
162163

163-
func (s *server) executor(workdir string, stage database.ProvisionerJobTimingStage) *executor {
164+
func (s *server) executor(workdir x.TerraformDirectory, stage database.ProvisionerJobTimingStage) *executor {
164165
return &executor{
165166
server: s,
166167
mut: s.execMut,

provisionerd/provisionerd_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ func TestProvisionerd(t *testing.T) {
353353
_ *sdkproto.ParseRequest,
354354
cancelOrComplete <-chan struct{},
355355
) *sdkproto.ParseComplete {
356-
data, err := os.ReadFile(filepath.Join(s.WorkDirectory, "test.txt"))
356+
data, err := os.ReadFile(filepath.Join(s.Files, "test.txt"))
357357
require.NoError(t, err)
358358
require.Equal(t, "content", string(data))
359359
s.ProvisionLog(sdkproto.LogLevel_INFO, "hello")

0 commit comments

Comments
 (0)