723 lines
27 KiB
Go
723 lines
27 KiB
Go
// Package main implements the IntegraCI db-migration Dagger module.
|
|
//
|
|
// Judges a service's migration SQL with IntegraCI's DB-change engine (the DBV
|
|
// policy engine behind the tenant's own policy, POST /api/v1/db-changes/analyze)
|
|
// and applies migrations with the tenant's own tool: liquibase (default — the
|
|
// engine the platform runs for its own database), flyway, or atlas. Which tool
|
|
// a tenant uses is the tenant's choice; atlas here is one of those choices, not
|
|
// the platform's (the platform retired atlas for its own schema in 2026-09).
|
|
//
|
|
// Verified 2026-09-26: `dagger functions` builds this module on engine v0.21.8.
|
|
// Before that date it was marked an unverified scaffold, and its lint could not
|
|
// fail for liquibase or flyway: `validate || true` swallowed every error, the
|
|
// destructive check grepped the tool's output (which carries no SQL), and the
|
|
// summary was POSTed to /services/{id}/migrations, which the API never served.
|
|
//
|
|
// Usage:
|
|
//
|
|
// dagger call lint --source . --dir migrations --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
|
// dagger call apply --source . --dir migrations --db-url env://DATABASE_URL --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"dagger/db-migration/engine"
|
|
"dagger/db-migration/internal/dagger"
|
|
"dagger/db-migration/verdict"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// DbMigration is the IntegraCI database migration module.
|
|
type DbMigration struct{}
|
|
|
|
// The images this module runs, pinned by tag AND digest (checked 2026-09-27):
|
|
// a bare tag is a question to the registry on every run, and an air-gapped
|
|
// mirror can only serve what it was given.
|
|
const (
|
|
// The Liquibase version the platform itself runs (apps/api/Dockerfile).
|
|
// Its JDBC drivers: postgresql, mssql-jdbc (SQL Server), ojdbc8 (Oracle),
|
|
// mariadb-java-client (MariaDB, and MySQL through a jdbc:mariadb: URL),
|
|
// jcc (DB2), jaybird (Firebird), snowflake, sqlite, h2, hsqldb. Not
|
|
// MySQL Connector/J: a jdbc:mysql: URL finds no driver.
|
|
liquibaseImage = "liquibase/liquibase:4.31.1-alpine@sha256:d7e17e2d234835fe132c4c46ec1af7d7d490710e882db162abb15593c4948fe8"
|
|
flywayImage = "flyway/flyway:10.22.0-alpine@sha256:94a81ca7db9a9f24fd8acd7463fa4560cb8f66aae2aa64485c27eb296f5851cf"
|
|
// Atlas Community Edition (Apache 2.0). The standard arigaio/atlas image
|
|
// is licensed under the proprietary Atlas MSA, and this module used it until
|
|
// 2026-09-27. Community supports PostgreSQL, MySQL, MariaDB and SQLite —
|
|
// not SQL Server or Oracle (https://atlasgo.io/community-edition).
|
|
atlasImage = "arigaio/atlas:1.3.3-community-alpine@sha256:9d3161bf3bf2b0ce6d0f6b63471d0a341e664e87cccec90a12139ea2cba18575"
|
|
// The throwaway database `atlas migrate lint` replays migrations on.
|
|
atlasDevPostgresImage = "postgres:16.13-alpine@sha256:4e6e670bb069649261c9c18031f0aded7bb249a5b6664ddec29c013a89310d50"
|
|
)
|
|
|
|
// engines are the migration-engine adapters (ADR-0070 §1), running the images
|
|
// pinned above. An adapter builds the command; this file binds the secrets and
|
|
// mounts only the judged files.
|
|
var engines = engine.New(engine.Images{Liquibase: liquibaseImage, Flyway: flywayImage, Atlas: atlasImage})
|
|
|
|
// defaultAdapter is the adapter the platform's grants are written for, if it
|
|
// drives the operation op. Asked before a grant is requested, so a default
|
|
// that cannot drive it fails without spending a grant nobody reports.
|
|
func defaultAdapter(drives func(engine.Capabilities) bool, op string) (engine.Adapter, error) {
|
|
adapter, err := engines.For(engine.DefaultTool)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !drives(adapter.Capabilities()) {
|
|
return nil, fmt.Errorf("%s %s: %w", adapter.Name(), op, engine.ErrUnsupported)
|
|
}
|
|
return adapter, nil
|
|
}
|
|
|
|
// LintReport summarises a migration lint run.
|
|
type LintReport struct {
|
|
Tool string `json:"tool"`
|
|
Dir string `json:"dir"`
|
|
// Destructive and security-sensitive statements across all files.
|
|
DestructiveFound int `json:"destructive_found"`
|
|
DestructiveList []string `json:"destructive_list"`
|
|
// The engine's verdict per migration file.
|
|
Verdicts []FileVerdict `json:"verdicts"`
|
|
// Output of the tool's own lint (atlas only; kept when it fails too).
|
|
Report string `json:"report"`
|
|
Skipped bool `json:"skipped,omitempty"`
|
|
Pass bool `json:"pass"`
|
|
}
|
|
|
|
// FileVerdict is the engine's verdict on one migration file.
|
|
type FileVerdict struct {
|
|
File string `json:"file"`
|
|
Decision string `json:"decision"`
|
|
Reasons []string `json:"reasons"`
|
|
Rules []string `json:"rules"`
|
|
RulesetVersion string `json:"ruleset_version"`
|
|
}
|
|
|
|
// ApplyResult contains the output of a migration apply run.
|
|
type ApplyResult struct {
|
|
Tool string `json:"tool"`
|
|
Dir string `json:"dir"`
|
|
Applied int `json:"applied"`
|
|
Pending int `json:"pending"`
|
|
Report string `json:"report"`
|
|
BlockedReason string `json:"blocked_reason,omitempty"`
|
|
Skipped bool `json:"skipped,omitempty"`
|
|
Success bool `json:"success"`
|
|
}
|
|
|
|
// Lint judges every migration file with IntegraCI's DB-change engine and fails
|
|
// on a change the tenant's policy blocks (or one needing approval, while
|
|
// blocking is on). For atlas it also runs `atlas migrate lint`, and fails when
|
|
// that does.
|
|
//
|
|
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
|
// by default, keyed on its arguments, so a second call would return the first
|
|
// call's verdict without judging, running or reporting anything.
|
|
// +cache="never"
|
|
func (m *DbMigration) Lint(
|
|
ctx context.Context,
|
|
// Source directory containing migrations
|
|
source *dagger.Directory,
|
|
// Migrations directory relative to source
|
|
// +optional
|
|
// +default="migrations"
|
|
dir string,
|
|
// Dev database URL atlas replays the migrations on — a secret, since a
|
|
// DSN carries a password. Unset: a throwaway PostgreSQL is started for
|
|
// this run (dialect postgres). The old default, docker://postgres/16/dev,
|
|
// needs a Docker CLI inside the atlas container and never worked here.
|
|
// +optional
|
|
devURL *dagger.Secret,
|
|
// Migration tool: liquibase | atlas | flyway | none
|
|
// +optional
|
|
// +default="liquibase"
|
|
tool string,
|
|
// Also fail on a change that needs approval (a blocked change always fails)
|
|
// +optional
|
|
// +default=true
|
|
blockDestructive bool,
|
|
// IntegraCI API URL — the engine that judges the SQL
|
|
// +optional
|
|
apiURL string,
|
|
// IntegraCI API token
|
|
// +optional
|
|
token *dagger.Secret,
|
|
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
|
// judges in the engines of the service's databases when --service-id is
|
|
// given, and as PostgreSQL otherwise
|
|
// +optional
|
|
dialect string,
|
|
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
|
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
|
// that engine's dialect, and one it has no rules for comes back unjudged,
|
|
// needing an approver (GET /api/v1/db-engines)
|
|
// +optional
|
|
engine string,
|
|
// Tenant environment id whose DB-change policy (and stage) applies
|
|
// +optional
|
|
environmentID string,
|
|
// The service these migrations belong to. With --version, the platform
|
|
// records its verdict for that release, which its deploy gate can require
|
|
// +optional
|
|
serviceID string,
|
|
// The version being built: the image tag the deploy will carry
|
|
// +optional
|
|
version string,
|
|
) (*LintReport, error) {
|
|
report := &LintReport{
|
|
Tool: tool,
|
|
Dir: dir,
|
|
DestructiveList: []string{},
|
|
Verdicts: []FileVerdict{},
|
|
Pass: true,
|
|
}
|
|
|
|
target, err := verdict.ResolveTarget(engine, dialect)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
|
return nil, err
|
|
}
|
|
// "none" disables DB migration governance — no-op skip.
|
|
if tool == "none" {
|
|
report.Skipped = true
|
|
return report, nil
|
|
}
|
|
|
|
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, report); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// The policy decides first. atlas lint REPLAYS the files on its dev
|
|
// database, so a file the policy refuses must never reach it (review,
|
|
// 2026-09-27: a blocked `COPY … TO PROGRAM` would otherwise run there).
|
|
refused, err := verdict.Refused(judged(report), blockDestructive)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(refused) > 0 {
|
|
report.Pass = false
|
|
return report, fmt.Errorf("lint: %d migration file(s) refused by the DB-change policy: %s",
|
|
len(refused), strings.Join(refused, "; "))
|
|
}
|
|
|
|
if tool == "atlas" {
|
|
rawOut, failed, err := m.atlasLint(ctx, source.Directory(dir), devURL, target.ToolDialect())
|
|
report.Report = rawOut
|
|
if err != nil {
|
|
return nil, fmt.Errorf("atlas lint could not run: %w", err)
|
|
}
|
|
if failed {
|
|
report.Pass = false
|
|
return report, fmt.Errorf("atlas migrate lint reported errors:\n%s", rawOut)
|
|
}
|
|
}
|
|
return report, nil
|
|
}
|
|
|
|
// Apply runs the migrations against the target database. It judges them first
|
|
// and refuses what the DB-change policy refuses: always a blocked change, and
|
|
// one that needs approval unless blockDestructive is off. The tool sees ONLY
|
|
// the judged directory — not the repo root, where a liquibase.properties or a
|
|
// flyway config could point it at SQL nobody judged.
|
|
//
|
|
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
|
// by default, keyed on its arguments, so a second call would return the first
|
|
// call's verdict without judging, running or reporting anything.
|
|
// +cache="never"
|
|
func (m *DbMigration) Apply(
|
|
ctx context.Context,
|
|
// Source directory containing migrations
|
|
source *dagger.Directory,
|
|
// Migrations directory relative to source
|
|
// +optional
|
|
// +default="migrations"
|
|
dir string,
|
|
// Target database URL (DATABASE_URL) to apply migrations to
|
|
// +optional
|
|
dbURL *dagger.Secret,
|
|
// Migration tool: liquibase | atlas | flyway | none
|
|
// +optional
|
|
// +default="liquibase"
|
|
tool string,
|
|
// Also refuse a change that needs approval (a blocked change is always refused)
|
|
// +optional
|
|
// +default=true
|
|
blockDestructive bool,
|
|
// IntegraCI API URL — the engine that judges the SQL
|
|
// +optional
|
|
apiURL string,
|
|
// IntegraCI API token
|
|
// +optional
|
|
token *dagger.Secret,
|
|
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
|
// judges in the engines of the service's databases when --service-id is
|
|
// given, and as PostgreSQL otherwise
|
|
// +optional
|
|
dialect string,
|
|
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
|
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
|
// that engine's dialect, and one it has no rules for comes back unjudged,
|
|
// needing an approver (GET /api/v1/db-engines)
|
|
// +optional
|
|
engine string,
|
|
// Tenant environment id whose DB-change policy (and stage) applies
|
|
// +optional
|
|
environmentID string,
|
|
// The service these migrations belong to (with --version; see lint)
|
|
// +optional
|
|
serviceID string,
|
|
// The version being built: the image tag the deploy will carry
|
|
// +optional
|
|
version string,
|
|
) (*ApplyResult, error) {
|
|
result := &ApplyResult{Tool: tool, Dir: dir}
|
|
target, err := verdict.ResolveTarget(engine, dialect)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// "none" disables DB migration governance — no-op skip.
|
|
if tool == "none" {
|
|
result.Skipped = true
|
|
result.Success = true
|
|
return result, nil
|
|
}
|
|
|
|
// Judge before touching the target DB — always.
|
|
lint := &LintReport{DestructiveList: []string{}, Verdicts: []FileVerdict{}}
|
|
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, lint); err != nil {
|
|
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
|
}
|
|
refused, err := verdict.Refused(judged(lint), blockDestructive)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
|
}
|
|
if len(refused) > 0 {
|
|
result.BlockedReason = strings.Join(refused, "; ")
|
|
return result, fmt.Errorf("apply blocked: %s", result.BlockedReason)
|
|
}
|
|
files := make([]string, 0, len(lint.Verdicts))
|
|
for _, v := range lint.Verdicts {
|
|
files = append(files, v.File)
|
|
}
|
|
|
|
rawOut, err := m.runApply(ctx, source.Directory(dir), tool, dbURL, files)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s apply failed: %w", tool, err)
|
|
}
|
|
result.Report = rawOut
|
|
result.Applied = verdict.AppliedCount(tool, rawOut)
|
|
result.Success = true
|
|
return result, nil
|
|
}
|
|
|
|
// Execute runs a batch the platform granted to this executor (plan §P5,
|
|
// integraci_db_apply_execution = "delegated"). It asks for a single-use grant
|
|
// for the dispatched batch digest, fetches the granted changelog, refuses it
|
|
// unless its SHA-256 is the one the grant names, runs it with Liquibase against
|
|
// --db-url, and reports the outcome once, so the platform's ledger records what
|
|
// ran. The platform never connects to the database.
|
|
//
|
|
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
|
// by default, keyed on its arguments, so a second call would return the first
|
|
// call's verdict without judging, running or reporting anything.
|
|
// +cache="never"
|
|
func (m *DbMigration) Execute(
|
|
ctx context.Context,
|
|
// IntegraCI API URL
|
|
apiURL string,
|
|
// IntegraCI API token of this tenant, with write on db_devops
|
|
apiToken *dagger.Secret,
|
|
// DbInstance id the batch was dispatched for
|
|
instanceID string,
|
|
// Batch digest (changeset_sha256) from the dispatched apply or rollback
|
|
digest string,
|
|
// Target database URL — a secret, never on the command line
|
|
dbURL *dagger.Secret,
|
|
// Roll back the last N applied changesets instead of applying (the count
|
|
// the dispatched rollback named); 0 applies
|
|
// +optional
|
|
// +default=0
|
|
rollbackCount int,
|
|
) (*ApplyResult, error) {
|
|
api, err := apiToken.Plaintext(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading the API token: %w", err)
|
|
}
|
|
client := verdict.NewClient()
|
|
grant, err := verdict.RequestGrant(ctx, client, apiURL, api, instanceID, digest, rollbackCount)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
file, err := granted.FileName()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
migrations := dag.Directory().WithNewFile(file, granted.Changelog)
|
|
ref := "dagger-" + grant.ChangelogSHA256[:12]
|
|
var out string
|
|
var runErr error
|
|
if rollbackCount > 0 {
|
|
out, runErr = m.runRollback(ctx, migrations, file, dbURL, rollbackCount)
|
|
} else {
|
|
out, runErr = m.runApply(ctx, migrations, engine.DefaultTool, dbURL, []string{file})
|
|
}
|
|
outcome, message := "applied", "applied by the tenant's executor"
|
|
if runErr != nil {
|
|
outcome, message = "failed", runErr.Error()
|
|
}
|
|
if err := verdict.Report(ctx, client, apiURL, api, *grant, outcome, ref, message); err != nil {
|
|
// The run happened; the ledger does not know. Say both.
|
|
return nil, fmt.Errorf("%s, and %w", outcome, err)
|
|
}
|
|
if runErr != nil {
|
|
return nil, fmt.Errorf("%s apply failed (reported): %w", engine.DefaultTool, runErr)
|
|
}
|
|
return &ApplyResult{Tool: engine.DefaultTool, Dir: "granted", Applied: len(granted.Changesets), Report: out, Success: true}, nil
|
|
}
|
|
|
|
// judge sends every migration file to IntegraCI's DB-change engine and records
|
|
// the verdicts in report. It fails closed: without an API to ask, with a
|
|
// changelog format the engine cannot read, or with a file the API will not
|
|
// take, nothing has judged the directory, so the step cannot pass.
|
|
func (m *DbMigration) judge(
|
|
ctx context.Context,
|
|
source *dagger.Directory,
|
|
dir, tool, apiURL string,
|
|
token *dagger.Secret,
|
|
target verdict.Target,
|
|
environmentID, serviceID, version string,
|
|
report *LintReport,
|
|
) error {
|
|
if apiURL == "" || token == nil {
|
|
return fmt.Errorf("--api-url and --token are required: the verdict comes from IntegraCI's DB-change engine, and without it nothing judges the SQL")
|
|
}
|
|
migrations := source.Directory(dir)
|
|
entries, err := migrations.Glob(ctx, "**/*")
|
|
if err != nil {
|
|
return fmt.Errorf("listing %s: %w", dir, err)
|
|
}
|
|
sqlFiles, unanalysable := verdict.SplitMigrations(entries)
|
|
if len(unanalysable) > 0 {
|
|
return fmt.Errorf("the DB-change engine reads SQL files; it cannot judge these (changelogs, other suffixes, symlinks): %s "+
|
|
"(use Liquibase formatted SQL, or --tool=none to opt out of governance)", strings.Join(unanalysable, ", "))
|
|
}
|
|
plain, err := token.Plaintext(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("reading the token: %w", err)
|
|
}
|
|
var env *string
|
|
if environmentID != "" {
|
|
env = &environmentID
|
|
}
|
|
service, release, err := verdict.Release(serviceID, version)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
client := verdict.NewClient()
|
|
for _, file := range sqlFiles {
|
|
sql, err := migrations.File(file).Contents(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("reading %s: %w", file, err)
|
|
}
|
|
if err := verdict.Judgeable(file, sql); err != nil {
|
|
return err
|
|
}
|
|
if tool == "liquibase" {
|
|
if err := verdict.LiquibaseJudgeable(file, sql); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if strings.TrimSpace(sql) == "" {
|
|
continue
|
|
}
|
|
name := file
|
|
resp, err := verdict.Analyze(ctx, client, apiURL, plain, verdict.Request{
|
|
SQL: sql, Dialect: target.Dialect, Engine: target.Engine, EnvironmentID: env,
|
|
ServiceID: service, Version: release, File: &name,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("judging %s: %w", file, err)
|
|
}
|
|
v := FileVerdict(verdict.Of(file, resp))
|
|
report.Verdicts = append(report.Verdicts, v)
|
|
report.DestructiveFound += resp.DestructiveCount + resp.SecurityCount
|
|
report.DestructiveList = append(report.DestructiveList, v.Rules...)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// judged converts the report's verdicts for the verdict package.
|
|
func judged(report *LintReport) []verdict.FileVerdict {
|
|
out := make([]verdict.FileVerdict, 0, len(report.Verdicts))
|
|
for _, v := range report.Verdicts {
|
|
out = append(out, verdict.FileVerdict(v))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// atlasLint runs atlas' own migration lint against a dev database — the given
|
|
// one, or, with none given, a throwaway PostgreSQL started for this run. Like
|
|
// runApply it sees the judged directory alone, with an empty working
|
|
// directory, so an atlas.hcl in the repo cannot change what it reads. It
|
|
// returns the lint's output and whether the lint failed; err is for a lint
|
|
// that could not run at all.
|
|
func (m *DbMigration) atlasLint(ctx context.Context, migrations *dagger.Directory, devURL *dagger.Secret, dialect string) (string, bool, error) {
|
|
ctr := dag.Container().
|
|
From(atlasImage).
|
|
WithDirectory("/migrations", migrations).
|
|
WithWorkdir("/work")
|
|
if devURL != nil {
|
|
ctr = ctr.WithSecretVariable("DEV_URL", devURL)
|
|
} else {
|
|
if dialect != "postgres" {
|
|
return "", false, fmt.Errorf("--dev-url is required for atlas with dialect %q: only a PostgreSQL dev database is started for you", dialect)
|
|
}
|
|
nonce := make([]byte, 8)
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return "", false, err
|
|
}
|
|
dev := dag.Container().
|
|
From(atlasDevPostgresImage).
|
|
// Reachable only through this binding, for this run. Trust auth: no
|
|
// password to leak. The nonce makes the service this run's own —
|
|
// two identical definitions could otherwise share one database.
|
|
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
|
WithEnvVariable("POSTGRES_DB", "dev").
|
|
WithEnvVariable("INTEGRACI_LINT_RUN", hex.EncodeToString(nonce)).
|
|
WithExposedPort(5432).
|
|
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
|
ctr = ctr.
|
|
WithServiceBinding("devdb", dev).
|
|
WithEnvVariable("DEV_URL", "postgres://postgres@devdb:5432/dev?sslmode=disable")
|
|
}
|
|
run := ctr.WithExec([]string{"sh", "-c",
|
|
`atlas migrate lint --dir file:///migrations --dev-url "$DEV_URL" --latest 1`,
|
|
}, dagger.ContainerWithExecOpts{Expect: dagger.ReturnTypeAny})
|
|
code, err := run.ExitCode(ctx)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
stdout, err := run.Stdout(ctx)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
stderr, err := run.Stderr(ctx)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
return strings.TrimSpace(stdout + "\n" + stderr), code != 0, nil
|
|
}
|
|
|
|
// runApply executes the tool-specific apply and returns its output. The tool
|
|
// gets the judged directory alone, mounted at /migrations, and an empty
|
|
// working directory, so no config file from the repo can widen what it runs.
|
|
// The target database URL is a secret env var, never on the command line.
|
|
// Liquibase runs each judged file as its own formatted-SQL changelog, in the
|
|
// order they were judged: there is no master changelog to point it at, and
|
|
// that is exactly the set the engine saw.
|
|
func (m *DbMigration) runApply(ctx context.Context, migrations *dagger.Directory, tool string, dbURL *dagger.Secret, files []string) (string, error) {
|
|
// verdict.CheckTool already refused an unknown tool; For refuses it again
|
|
// rather than fall through to another tool.
|
|
adapter, err := engines.For(tool)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cmd, err := adapter.Apply(files)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return dag.Container().
|
|
From(cmd.Image).
|
|
WithSecretVariable("DATABASE_URL", dbURL).
|
|
WithDirectory("/migrations", migrations).
|
|
WithWorkdir("/work").
|
|
WithExec(cmd.Args).
|
|
Stdout(ctx)
|
|
}
|
|
|
|
// Drift checks the tenant's database for drift under a platform-issued drift
|
|
// grant, and reports it once. The reference is NOT the executor's choice: the
|
|
// grant names the instance's applied changelog, which is built into a
|
|
// throwaway PostgreSQL (or into --reference-url, an EMPTY database of the same
|
|
// engine, for another dialect) and diffed against the live database. Until
|
|
// 2026-09-27 the executor passed any reference URL and the report took no
|
|
// grant, so it proved nothing (plan §7, "self-attested").
|
|
//
|
|
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
|
// by default, keyed on its arguments, so a second call would return the first
|
|
// call's verdict without judging, running or reporting anything.
|
|
// +cache="never"
|
|
func (m *DbMigration) Drift(
|
|
ctx context.Context,
|
|
// IntegraCI API URL
|
|
apiURL string,
|
|
// IntegraCI API token of this tenant, with write on db_devops
|
|
apiToken *dagger.Secret,
|
|
// DbInstance id to report drift for
|
|
instanceID string,
|
|
// The live database URL (JDBC) — a secret
|
|
dbURL *dagger.Secret,
|
|
// A reference to this run (CI job URL or id), kept with the report
|
|
executionRef string,
|
|
// An EMPTY database of the live database's engine to build the reference
|
|
// in (JDBC, a secret). Unset: a throwaway PostgreSQL for this run.
|
|
// +optional
|
|
referenceURL *dagger.Secret,
|
|
) (*DriftResult, error) {
|
|
// Before the grant: one the adapter cannot use would be spent unreported.
|
|
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Drift }, "drift")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
api, err := apiToken.Plaintext(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading the API token: %w", err)
|
|
}
|
|
client := verdict.NewClient()
|
|
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "drift")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
file, err := granted.FileName()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cmd, err := adapter.Drift(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ctr := dag.Container().
|
|
From(cmd.Image).
|
|
WithSecretVariable("DATABASE_URL", dbURL).
|
|
WithDirectory("/reference", dag.Directory().WithNewFile(file, granted.Changelog)).
|
|
WithWorkdir("/work").
|
|
// This grant's own run: never a cached diff from an earlier one.
|
|
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI)
|
|
if referenceURL != nil {
|
|
ctr = ctr.WithSecretVariable("REFERENCE_URL", referenceURL)
|
|
} else {
|
|
ref := dag.Container().
|
|
From(atlasDevPostgresImage).
|
|
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
|
WithEnvVariable("POSTGRES_DB", "reference").
|
|
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI).
|
|
WithExposedPort(5432).
|
|
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
|
ctr = ctr.
|
|
WithServiceBinding("refdb", ref).
|
|
WithEnvVariable("REFERENCE_URL", "jdbc:postgresql://refdb:5432/reference?user=postgres")
|
|
}
|
|
out, err := ctr.WithExec(cmd.Args).Stdout(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("building the reference or diffing against it failed: %w", err)
|
|
}
|
|
report := verdict.DriftReport{Drifted: verdict.Drifted(out), Diff: out, ExecutionRef: executionRef}
|
|
if err := verdict.ReportDrift(ctx, client, apiURL, api, *grant, report); err != nil {
|
|
return nil, err
|
|
}
|
|
return &DriftResult{Drifted: report.Drifted, Report: out}, nil
|
|
}
|
|
|
|
// Snapshot takes a schema snapshot of the tenant's database under a snapshot
|
|
// grant and records it on the platform (its hash and size, as an in-process
|
|
// snapshot is not stored either). Returns the snapshot JSON.
|
|
//
|
|
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
|
// by default, keyed on its arguments, so a second call would return the first
|
|
// call's verdict without judging, running or reporting anything.
|
|
// +cache="never"
|
|
func (m *DbMigration) Snapshot(
|
|
ctx context.Context,
|
|
// IntegraCI API URL
|
|
apiURL string,
|
|
// IntegraCI API token of this tenant, with write on db_devops
|
|
apiToken *dagger.Secret,
|
|
// DbInstance id the snapshot is of
|
|
instanceID string,
|
|
// The live database URL (JDBC) — a secret
|
|
dbURL *dagger.Secret,
|
|
// A reference to this run (CI job URL or id)
|
|
executionRef string,
|
|
) (string, error) {
|
|
// Before the grant: one the adapter cannot use would be spent unreported.
|
|
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Snapshot }, "snapshot")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
api, err := apiToken.Plaintext(ctx)
|
|
if err != nil {
|
|
return "", fmt.Errorf("reading the API token: %w", err)
|
|
}
|
|
client := verdict.NewClient()
|
|
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "snapshot")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cmd, err := adapter.Snapshot()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
out, runErr := dag.Container().
|
|
From(cmd.Image).
|
|
WithSecretVariable("DATABASE_URL", dbURL).
|
|
WithWorkdir("/work").
|
|
// This grant's own run: never a cached snapshot from an earlier one.
|
|
WithEnvVariable("INTEGRACI_SNAPSHOT_GRANT", grant.JTI).
|
|
WithExec(cmd.Args).
|
|
Stdout(ctx)
|
|
outcome, message := "taken", ""
|
|
if runErr != nil {
|
|
outcome, message, out = "failed", runErr.Error(), ""
|
|
}
|
|
if err := verdict.ReportSnapshot(ctx, client, apiURL, api, *grant, outcome, out, executionRef, message); err != nil {
|
|
return "", fmt.Errorf("%s, and %w", outcome, err)
|
|
}
|
|
if runErr != nil {
|
|
return "", fmt.Errorf("%s snapshot failed (reported): %w", engine.DefaultTool, runErr)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// DriftResult is what Drift found and reported.
|
|
type DriftResult struct {
|
|
Drifted bool
|
|
Report string
|
|
}
|
|
|
|
// runRollback undoes the last n changesets of the granted changelog with the
|
|
// default adapter, against the judged file alone (see runApply).
|
|
func (m *DbMigration) runRollback(ctx context.Context, migrations *dagger.Directory, file string, dbURL *dagger.Secret, n int) (string, error) {
|
|
adapter, err := engines.For(engine.DefaultTool)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cmd, err := adapter.Rollback(file, n)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return dag.Container().
|
|
From(cmd.Image).
|
|
WithSecretVariable("DATABASE_URL", dbURL).
|
|
WithDirectory("/migrations", migrations).
|
|
WithWorkdir("/work").
|
|
WithExec(cmd.Args).
|
|
Stdout(ctx)
|
|
}
|