426 lines
16 KiB
Go
426 lines
16 KiB
Go
package rehearsal
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.maximumdirect.net/releasekit/internal/artifact"
|
|
"go.maximumdirect.net/releasekit/internal/forge"
|
|
"go.maximumdirect.net/releasekit/internal/git"
|
|
"go.maximumdirect.net/releasekit/internal/readiness"
|
|
"go.maximumdirect.net/releasekit/internal/releaseidentity"
|
|
"go.maximumdirect.net/releasekit/internal/woodpecker"
|
|
)
|
|
|
|
type JobObservation struct {
|
|
PipelineID int64 `json:"pipeline_id"`
|
|
PipelineNumber int64 `json:"pipeline_number"`
|
|
WorkflowID int64 `json:"workflow_id"`
|
|
StepID int64 `json:"step_id"`
|
|
PipelineStatus string `json:"pipeline_status"`
|
|
WorkflowState string `json:"workflow_state"`
|
|
StepState string `json:"step_state"`
|
|
}
|
|
|
|
type WorkflowObservation struct {
|
|
PipelineID int64 `json:"pipeline_id"`
|
|
PipelineNumber int64 `json:"pipeline_number"`
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
State string `json:"state"`
|
|
}
|
|
|
|
type StartRequest struct {
|
|
RepositoryDir, Ref, ProfilePath, ModuleDir, Product, Selector string
|
|
Source *releaseidentity.SourceSpec
|
|
Remote, ExpectedPushURL, RecordDir string
|
|
Build *artifact.Settings
|
|
RequiredFiles []string
|
|
ForgeBaseURL, ForgeOwner, ForgeRepository string
|
|
Backend forge.Backend
|
|
Woodpecker woodpecker.Client
|
|
Workflow, Step string
|
|
CIConfigured bool
|
|
ObservationTimeout time.Duration
|
|
Output io.Writer
|
|
}
|
|
type Outcome struct {
|
|
Attempt Attempt
|
|
RecordPath string
|
|
Workflow, Build, Verification, Cleanup string
|
|
Diagnostics []string
|
|
}
|
|
|
|
// Start captures and records an attempt before pushing its diagnostic tag.
|
|
func Start(ctx context.Context, request StartRequest) (Outcome, error) {
|
|
result := Outcome{Workflow: "not_started", Build: "not_started", Verification: "not_started", Cleanup: "pending"}
|
|
if request.ObservationTimeout < 0 {
|
|
return result, errors.New("observation timeout cannot be negative")
|
|
}
|
|
if err := readiness.CheckCIConfigured(request.CIConfigured); err != nil {
|
|
return result, err
|
|
}
|
|
if request.Backend == nil {
|
|
return result, errors.New("delivery backend is required")
|
|
}
|
|
if request.Workflow == "" || request.Step == "" {
|
|
return result, errors.New("Woodpecker workflow and step are required")
|
|
}
|
|
repo, err := git.RepositoryRoot(ctx, request.RepositoryDir)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
commit, err := git.ResolveCommit(ctx, repo, request.Ref)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
profilePath := request.ProfilePath
|
|
if profilePath == "" {
|
|
profilePath = "releasekit.json"
|
|
}
|
|
if filepath.IsAbs(profilePath) {
|
|
profilePath, err = filepath.Rel(repo, filepath.Clean(profilePath))
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
}
|
|
profilePath = filepath.ToSlash(filepath.Clean(profilePath))
|
|
profile, err := git.ReadCommitFile(ctx, repo, commit, profilePath)
|
|
if err != nil {
|
|
return result, fmt.Errorf("rehearsal profile must be committed within the checkout: %w", err)
|
|
}
|
|
var declarations struct {
|
|
Delivery *struct {
|
|
Credentials *struct {
|
|
CI *struct{} `json:"ci"`
|
|
} `json:"credentials"`
|
|
} `json:"delivery"`
|
|
}
|
|
if err := json.Unmarshal(profile, &declarations); err != nil || declarations.Delivery == nil || declarations.Delivery.Credentials == nil || declarations.Delivery.Credentials.CI == nil {
|
|
return result, errors.New("committed profile must declare CI delivery credentials")
|
|
}
|
|
source, err := releaseidentity.LoadCommittedSource(ctx, repo, request.ModuleDir, commit, request.Source)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
selector := request.Selector
|
|
if selector == "" {
|
|
selector = "root"
|
|
}
|
|
identity, attemptID, err := releaseidentity.NewDiagnostic(ctx, source, selector, commit)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
manifest := NewManifest(identity, attemptID, selector, profilePath, profile)
|
|
remote := request.Remote
|
|
if remote == "" {
|
|
remote = "origin"
|
|
}
|
|
wood := request.Woodpecker
|
|
input := readiness.Request{RepositoryDir: repo, ModuleDir: request.ModuleDir, Product: request.Product, Remote: remote, ExpectedPushURL: request.ExpectedPushURL, Context: "local", Commit: commit, Source: request.Source, Operations: []string{"rehearsal"}, Build: request.Build, HasDelivery: true, HasRehearsal: true, RequiredFiles: request.RequiredFiles,
|
|
DeliveryConfig: func() error {
|
|
if v, ok := request.Backend.(interface{ ValidateConfiguration() error }); ok {
|
|
return v.ValidateConfiguration()
|
|
}
|
|
return errors.New("delivery settings cannot be validated")
|
|
},
|
|
Credential: func() error { return nil }, Delivery: request.Backend.Preflight, RehearsalConfig: wood.ValidateConfiguration, Rehearsal: wood.CheckRepository}
|
|
input.CIConfigured, input.Selector = request.CIConfigured, selector
|
|
checked := readiness.Run(ctx, input)
|
|
var failures []error
|
|
for _, check := range checked.Checks {
|
|
if check.Status == "failed" {
|
|
if check.Cause != nil {
|
|
failures = append(failures, fmt.Errorf("%s: %w", check.ID, check.Cause))
|
|
} else {
|
|
failures = append(failures, errors.New(check.Message))
|
|
}
|
|
}
|
|
if check.Status == "unchecked" && check.Reason == "unavailable" {
|
|
failures = append(failures, errors.New(check.Message))
|
|
}
|
|
}
|
|
if len(failures) > 0 {
|
|
return result, fmt.Errorf("rehearsal readiness: %w", errors.Join(failures...))
|
|
}
|
|
endpoint, err := git.Resolve(ctx, repo, remote)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
if request.ExpectedPushURL != "" && endpoint.PushURL != request.ExpectedPushURL {
|
|
return result, errors.New("publication endpoint does not match expected endpoint")
|
|
}
|
|
remoteTag, err := endpoint.QueryTag(ctx, repo, identity.Tag)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
if remoteTag.State != git.RefAbsent {
|
|
return result, fmt.Errorf("diagnostic tag already exists: %w", git.ErrRemoteTagConflict)
|
|
}
|
|
note := DiagnosticNote(request.Product, manifest)
|
|
digest := sha256.Sum256([]byte(note))
|
|
attempt := Attempt{Manifest: manifest, RepositoryDir: repo, Endpoint: endpoint.PushURL, Remote: remote, ForgeBaseURL: request.ForgeBaseURL, ForgeOwner: request.ForgeOwner, ForgeRepository: request.ForgeRepository, WoodpeckerBaseURL: wood.BaseURL, WoodpeckerRepositoryID: wood.RepositoryID, Workflow: request.Workflow, Step: request.Step, ExpectedPageTitle: strings.TrimPrefix(strings.SplitN(note, "\n", 2)[0], "# "), ExpectedBodySHA256: hex.EncodeToString(digest[:]), Outcomes: map[string]string{"tag": "planned", "push": "not_attempted", "workflow": "not_started", "verification": "not_started", "cleanup": "pending"}}
|
|
if request.Build != nil && len(request.Build.Targets) > 0 {
|
|
settings := artifact.NormalizeSettings(request.Build.MainPackage, request.Build.BinaryName, request.Build.Targets)
|
|
for _, item := range artifact.ExpectedBuild(settings.BinaryName, identity.Version, settings.Targets) {
|
|
attempt.PlannedAssets = append(attempt.PlannedAssets, item.Filename)
|
|
}
|
|
attempt.PlannedAssets = append(attempt.PlannedAssets, artifact.ManifestFilename)
|
|
}
|
|
store, err := CreateAttempt(ctx, repo, request.RecordDir, attempt)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
result.RecordPath = store.Path
|
|
result.Attempt = attempt
|
|
save := func() error { result.Attempt = attempt; return store.Save(attempt) }
|
|
attempt.Outcomes["tag"] = "creating"
|
|
if err := save(); err != nil {
|
|
return result, fmt.Errorf("record tag intent: %w", err)
|
|
}
|
|
object, tagErr := CreateDiagnosticTag(ctx, repo, manifest)
|
|
if object != "" {
|
|
attempt.TagObject = object
|
|
}
|
|
if tagErr != nil {
|
|
attempt.Outcomes["tag"] = "unknown"
|
|
saveErr := save()
|
|
return result, errors.Join(tagErr, saveErr)
|
|
}
|
|
attempt.Outcomes["tag"] = "created"
|
|
if err := save(); err != nil {
|
|
return result, fmt.Errorf("record diagnostic tag: %w", err)
|
|
}
|
|
attempt.Outcomes["push"] = "attempting"
|
|
if err := save(); err != nil {
|
|
return result, fmt.Errorf("record push intent: %w", err)
|
|
}
|
|
pushErr := endpoint.PushDiagnosticTag(ctx, repo, identity.Tag, object, commit)
|
|
if pushErr != nil {
|
|
attempt.Outcomes["push"] = "unknown"
|
|
observed, observeErr := endpoint.QueryTag(ctx, repo, identity.Tag)
|
|
if observeErr == nil && observed.State == git.RefPresent && git.EqualObjectID(observed.Object, object) && git.EqualObjectID(observed.Peeled, commit) {
|
|
attempt.Outcomes["push"] = "dispatched"
|
|
} else {
|
|
saveErr := save()
|
|
return result, errors.Join(pushErr, observeErr, saveErr)
|
|
}
|
|
} else {
|
|
attempt.Outcomes["push"] = "dispatched"
|
|
}
|
|
if err := save(); err != nil {
|
|
return result, fmt.Errorf("record diagnostic push: %w", err)
|
|
}
|
|
if request.Output != nil {
|
|
if _, err := fmt.Fprintf(request.Output, "diagnostic attempt %s recorded at %s\n", attemptID, git.DisplayDiagnostic(store.Path)); err != nil {
|
|
return result, fmt.Errorf("write rehearsal progress: %w", err)
|
|
}
|
|
}
|
|
observationCtx := ctx
|
|
cancel := func() {}
|
|
if request.ObservationTimeout > 0 {
|
|
observationCtx, cancel = context.WithTimeout(ctx, request.ObservationTimeout)
|
|
}
|
|
defer cancel()
|
|
result, err = observe(observationCtx, wood, request.Workflow, request.Step, store, attempt, result)
|
|
return result, err
|
|
}
|
|
|
|
func observe(ctx context.Context, client woodpecker.Client, workflow, step string, store *Store, attempt Attempt, result Outcome) (outcome Outcome, resultErr error) {
|
|
defer func() { outcome.Attempt = attempt }()
|
|
save := func() error { result.Attempt = attempt; return store.Save(attempt) }
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
attempt.Outcomes["workflow"] = "unknown"
|
|
result.Workflow = "unknown"
|
|
return result, errors.Join(err, save())
|
|
}
|
|
pipelines, err := client.MatchingPipelines(ctx, attempt.Manifest.Tag, attempt.Manifest.Commit)
|
|
if err != nil {
|
|
attempt.Outcomes["workflow"] = "unknown"
|
|
result.Workflow = "unknown"
|
|
return result, errors.Join(err, save())
|
|
}
|
|
terminalOnly := len(pipelines) > 0
|
|
var success *JobResult
|
|
var failed bool
|
|
var workflowComplete bool
|
|
jobs := make([]JobObservation, 0)
|
|
workflows := make([]WorkflowObservation, 0)
|
|
for _, listed := range pipelines {
|
|
if !containsID(attempt.PipelineIDs, listed.ID) {
|
|
attempt.PipelineIDs = append(attempt.PipelineIDs, listed.ID)
|
|
attempt.PipelineNumbers = append(attempt.PipelineNumbers, listed.Number)
|
|
}
|
|
detail, err := client.DiagnosticPipeline(ctx, listed.Number, attempt.Manifest.Tag, attempt.Manifest.Commit)
|
|
if err != nil {
|
|
attempt.Outcomes["workflow"] = "unknown"
|
|
result.Workflow = "unknown"
|
|
return result, errors.Join(err, save())
|
|
}
|
|
if detail.ID != listed.ID {
|
|
return result, errors.Join(errors.New("pipeline identity changed during observation"), save())
|
|
}
|
|
for _, observed := range detail.Workflows {
|
|
workflows = append(workflows, WorkflowObservation{PipelineID: detail.ID, PipelineNumber: detail.Number, ID: observed.ID, Name: observed.Name, State: observed.State})
|
|
}
|
|
if woodpecker.StateClass(detail.Status) != "terminal" {
|
|
terminalOnly = false
|
|
}
|
|
selected, selectionErr := detail.Jobs(workflow, step)
|
|
if selectionErr != nil {
|
|
if woodpecker.StateClass(detail.Status) == "terminal" {
|
|
failed = true
|
|
}
|
|
continue
|
|
}
|
|
for _, job := range selected {
|
|
jobs = append(jobs, JobObservation{PipelineID: job.PipelineID, PipelineNumber: job.PipelineNumber, WorkflowID: job.WorkflowID, StepID: job.StepID, PipelineStatus: job.PipelineStatus, WorkflowState: job.WorkflowState, StepState: job.StepState})
|
|
if job.WorkflowState != "success" || job.StepState != "success" {
|
|
if woodpecker.StateClass(job.WorkflowState) == "terminal" || woodpecker.StateClass(job.StepState) == "terminal" && job.StepState != "success" {
|
|
failed = true
|
|
if woodpecker.StateClass(job.StepState) == "terminal" {
|
|
if stream, err := client.OpenLog(ctx, job.PipelineNumber, job.StepID); err == nil {
|
|
evidence, readErr := ReadResult(stream, attempt.Manifest)
|
|
closeErr := stream.Close()
|
|
if readErr != nil && !errors.Is(readErr, ErrResultAbsent) || closeErr != nil {
|
|
attempt.Jobs, attempt.Workflows = jobs, workflows
|
|
attempt.Outcomes["workflow"], attempt.Outcomes["verification"] = "failed", "incomplete"
|
|
result.Workflow, result.Verification = "failed", "incomplete"
|
|
return result, errors.Join(readErr, closeErr, save())
|
|
}
|
|
if readErr == nil && closeErr == nil {
|
|
attempt.JobEvidence = &evidence
|
|
attempt.PageID = evidence.PageID
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
terminalOnly = false
|
|
}
|
|
continue
|
|
}
|
|
workflowComplete = true
|
|
stream, err := client.OpenLog(ctx, job.PipelineNumber, job.StepID)
|
|
if err != nil {
|
|
attempt.Jobs = jobs
|
|
attempt.Workflows = workflows
|
|
attempt.Outcomes["workflow"] = "complete"
|
|
attempt.Outcomes["verification"] = "incomplete"
|
|
result.Workflow, result.Verification = "complete", "incomplete"
|
|
return result, errors.Join(err, save())
|
|
}
|
|
evidence, readErr := ReadResult(stream, attempt.Manifest)
|
|
closeErr := stream.Close()
|
|
if err := errors.Join(readErr, closeErr); err != nil {
|
|
attempt.Jobs = jobs
|
|
attempt.Workflows = workflows
|
|
attempt.Outcomes["workflow"] = "complete"
|
|
attempt.Outcomes["verification"] = "incomplete"
|
|
result.Workflow, result.Verification = "complete", "incomplete"
|
|
return result, errors.Join(err, save())
|
|
}
|
|
if evidence.Verification != "complete" || evidence.Delivery != "complete" {
|
|
failed = true
|
|
attempt.JobEvidence = &evidence
|
|
attempt.PageID = evidence.PageID
|
|
continue
|
|
}
|
|
if !matchesPlannedAssets(attempt.PlannedAssets, evidence.Artifacts) {
|
|
attempt.Jobs, attempt.Workflows = jobs, workflows
|
|
attempt.Outcomes["workflow"], attempt.Outcomes["verification"] = "complete", "incomplete"
|
|
result.Workflow, result.Verification = "complete", "incomplete"
|
|
return result, errors.Join(errors.New("verified assets do not match the recorded plan"), save())
|
|
}
|
|
if success != nil {
|
|
left, _ := EncodeResult(*success)
|
|
right, _ := EncodeResult(evidence)
|
|
if !bytes.Equal(left, right) {
|
|
return result, errors.Join(errors.New("matching jobs returned conflicting evidence"), save())
|
|
}
|
|
}
|
|
copy := evidence
|
|
success = ©
|
|
}
|
|
}
|
|
attempt.Jobs = jobs
|
|
attempt.Workflows = workflows
|
|
if success != nil {
|
|
attempt.JobEvidence = success
|
|
attempt.PageID = success.PageID
|
|
attempt.Outcomes["workflow"] = "complete"
|
|
attempt.Outcomes["build"] = success.Build
|
|
attempt.Outcomes["verification"] = "complete"
|
|
result.Workflow = "complete"
|
|
result.Build = success.Build
|
|
result.Verification = "complete"
|
|
return result, save()
|
|
}
|
|
if terminalOnly && failed {
|
|
attempt.Outcomes["workflow"] = "failed"
|
|
attempt.Outcomes["verification"] = "incomplete"
|
|
result.Workflow = "failed"
|
|
result.Verification = "incomplete"
|
|
if workflowComplete {
|
|
attempt.Outcomes["workflow"] = "complete"
|
|
result.Workflow = "complete"
|
|
}
|
|
if attempt.JobEvidence != nil {
|
|
result.Build = attempt.JobEvidence.Build
|
|
attempt.Outcomes["build"] = result.Build
|
|
}
|
|
return result, errors.Join(errors.New("matching CI delivery did not complete successfully"), save())
|
|
}
|
|
attempt.Outcomes["workflow"] = "waiting"
|
|
result.Workflow = "waiting"
|
|
if err := save(); err != nil {
|
|
return result, err
|
|
}
|
|
timer := time.NewTimer(time.Second)
|
|
select {
|
|
case <-ctx.Done():
|
|
if !timer.Stop() {
|
|
<-timer.C
|
|
}
|
|
attempt.Outcomes["workflow"] = "unknown"
|
|
result.Workflow = "unknown"
|
|
return result, errors.Join(ctx.Err(), save())
|
|
case <-timer.C:
|
|
}
|
|
}
|
|
}
|
|
func containsID(values []int64, value int64) bool {
|
|
for _, item := range values {
|
|
if item == value {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func matchesPlannedAssets(planned []string, observed []ArtifactEvidence) bool {
|
|
if len(planned) != len(observed) {
|
|
return false
|
|
}
|
|
want := make(map[string]bool, len(planned))
|
|
for _, name := range planned {
|
|
want[name] = true
|
|
}
|
|
for _, item := range observed {
|
|
if !want[item.Name] {
|
|
return false
|
|
}
|
|
delete(want, item.Name)
|
|
}
|
|
return len(want) == 0
|
|
}
|