Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix: reduce size of terraform modules archive #17749

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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ site/stats/
*.tfplan
*.lock.hcl
.terraform/
!provisioner/terraform/testdata/modules-source-caching/.terraform/

**/.coderv2/*
**/__debug_bin
Expand Down
2 changes: 1 addition & 1 deletion cli/testdata/coder_provisioner_list_--output_json.golden
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"last_seen_at": "====[timestamp]=====",
"name": "test",
"version": "v0.0.0-devel",
"api_version": "1.4",
"api_version": "1.5",
"provisioners": [
"echo"
],
Expand Down
11 changes: 5 additions & 6 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,19 @@ import (
"time"

"github.com/google/uuid"
"golang.org/x/xerrors"

"github.com/open-policy-agent/opa/topdown"
"golang.org/x/xerrors"

"cdr.dev/slog"

"github.com/coder/coder/v2/coderd/prebuilds"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/rbac/rolestore"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpapi/httpapiconstraints"
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
"github.com/coder/coder/v2/coderd/prebuilds"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/rbac/rolestore"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/provisionersdk"
)
Expand Down Expand Up @@ -347,6 +345,7 @@ var (
rbac.ResourceNotificationPreference.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceNotificationTemplate.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceCryptoKey.Type: {policy.ActionCreate, policy.ActionUpdate, policy.ActionDelete},
rbac.ResourceFile.Type: {policy.ActionCreate, policy.ActionRead},
}),
Org: map[string][]rbac.Permission{},
User: []rbac.Permission{},
Expand Down
7 changes: 4 additions & 3 deletions coderd/database/dbgen/dbgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -999,9 +999,10 @@ func TemplateVersionTerraformValues(t testing.TB, db database.Store, orig databa
t.Helper()

params := database.InsertTemplateVersionTerraformValuesByJobIDParams{
JobID: takeFirst(orig.JobID, uuid.New()),
CachedPlan: takeFirstSlice(orig.CachedPlan, []byte("{}")),
UpdatedAt: takeFirst(orig.UpdatedAt, dbtime.Now()),
JobID: takeFirst(orig.JobID, uuid.New()),
CachedPlan: takeFirstSlice(orig.CachedPlan, []byte("{}")),
CachedModuleFiles: orig.CachedModuleFiles,
UpdatedAt: takeFirst(orig.UpdatedAt, dbtime.Now()),
}

err := db.InsertTemplateVersionTerraformValuesByJobID(genCtx, params)
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -9315,6 +9315,7 @@ func (q *FakeQuerier) InsertTemplateVersionTerraformValuesByJobID(_ context.Cont
row := database.TemplateVersionTerraformValue{
TemplateVersionID: templateVersion.ID,
CachedPlan: arg.CachedPlan,
CachedModuleFiles: arg.CachedModuleFiles,
UpdatedAt: arg.UpdatedAt,
}
q.templateVersionTerraformValues = append(q.templateVersionTerraformValues, row)
Expand Down
6 changes: 5 additions & 1 deletion coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions coderd/database/foreign_key_constraint.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE template_version_terraform_values DROP COLUMN cached_module_files;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE template_version_terraform_values ADD COLUMN cached_module_files uuid references files(id);
1 change: 1 addition & 0 deletions coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 20 additions & 7 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions coderd/database/queries/templateversionterraformvalues.sql
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ INSERT INTO
template_version_terraform_values (
template_version_id,
cached_plan,
cached_module_files,
updated_at
)
VALUES
(
(select id from template_versions where job_id = @job_id),
@cached_plan,
@cached_module_files,
@updated_at
);
64 changes: 59 additions & 5 deletions coderd/provisionerdserver/provisionerdserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package provisionerdserver

import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -50,6 +52,10 @@ import (
sdkproto "github.com/coder/coder/v2/provisionersdk/proto"
)

const (
tarMimeType = "application/x-tar"
)

const (
// DefaultAcquireJobLongPollDur is the time the (deprecated) AcquireJob rpc waits to try to obtain a job before
// canceling and returning an empty job.
Expand Down Expand Up @@ -1426,11 +1432,59 @@ func (s *server) CompleteJob(ctx context.Context, completed *proto.CompletedJob)
return nil, xerrors.Errorf("update template version external auth providers: %w", err)
}

if len(jobType.TemplateImport.Plan) > 0 {
err := s.Database.InsertTemplateVersionTerraformValuesByJobID(ctx, database.InsertTemplateVersionTerraformValuesByJobIDParams{
JobID: jobID,
CachedPlan: jobType.TemplateImport.Plan,
UpdatedAt: now,
plan := jobType.TemplateImport.Plan
moduleFiles := jobType.TemplateImport.ModuleFiles
// If there is a plan, or a module files archive we need to insert a
// template_version_terraform_values row.
if len(plan) > 0 || len(moduleFiles) > 0 {
// ...but the plan and the module files archive are both optional! So
// we need to fallback to a valid JSON object if the plan was omitted.
if len(plan) == 0 {
plan = []byte("{}")
}

// ...and we only want to insert a files row if an archive was provided.
var fileID uuid.NullUUID
if len(moduleFiles) > 0 {
hashBytes := sha256.Sum256(moduleFiles)
hash := hex.EncodeToString(hashBytes[:])

// nolint:gocritic // Requires reading "system" files
file, err := s.Database.GetFileByHashAndCreator(dbauthz.AsSystemRestricted(ctx), database.GetFileByHashAndCreatorParams{Hash: hash, CreatedBy: uuid.Nil})
switch {
case err == nil:
// This set of modules is already cached, which means we can reuse them
fileID = uuid.NullUUID{
Valid: true,
UUID: file.ID,
}
case !xerrors.Is(err, sql.ErrNoRows):
return nil, xerrors.Errorf("check for cached modules: %w", err)
default:
// nolint:gocritic // Requires creating a "system" file
file, err = s.Database.InsertFile(dbauthz.AsSystemRestricted(ctx), database.InsertFileParams{
ID: uuid.New(),
Hash: hash,
CreatedBy: uuid.Nil,
CreatedAt: dbtime.Now(),
Mimetype: tarMimeType,
Data: moduleFiles,
})
if err != nil {
return nil, xerrors.Errorf("insert template version terraform modules: %w", err)
}
fileID = uuid.NullUUID{
Valid: true,
UUID: file.ID,
}
}
}

err = s.Database.InsertTemplateVersionTerraformValuesByJobID(ctx, database.InsertTemplateVersionTerraformValuesByJobIDParams{
JobID: jobID,
UpdatedAt: now,
CachedPlan: plan,
CachedModuleFiles: fileID,
})
if err != nil {
return nil, xerrors.Errorf("insert template version terraform data: %w", err)
Expand Down
4 changes: 3 additions & 1 deletion provisioner/echo/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ var (
PlanComplete = []*proto.Response{{
Type: &proto.Response_Plan{
Plan: &proto.PlanComplete{
Plan: []byte("{}"),
Plan: []byte("{}"),
ModuleFiles: []byte{},
},
},
}}
Expand Down Expand Up @@ -249,6 +250,7 @@ func TarWithOptions(ctx context.Context, logger slog.Logger, responses *Response
Parameters: resp.GetApply().GetParameters(),
ExternalAuthProviders: resp.GetApply().GetExternalAuthProviders(),
Plan: []byte("{}"),
ModuleFiles: []byte{},
}},
})
}
Expand Down
7 changes: 7 additions & 0 deletions provisioner/terraform/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,20 @@ func (e *executor) plan(ctx, killCtx context.Context, env, vars []string, logr l

graphTimings.ingest(createGraphTimingsEvent(timingGraphComplete))

moduleFiles, err := getModulesArchive(e.workdir)
if err != nil {
// TODO: we probably want to persist this error or make it louder eventually
e.logger.Warn(ctx, "failed to archive terraform modules", slog.Error(err))
}

return &proto.PlanComplete{
Parameters: state.Parameters,
Resources: state.Resources,
ExternalAuthProviders: state.ExternalAuthProviders,
Timings: append(e.timings.aggregate(), graphTimings.aggregate()...),
Presets: state.Presets,
Plan: plan,
ModuleFiles: moduleFiles,
}, nil
}

Expand Down
Loading
Loading