Documentation
¶
Overview ¶
Package lifecycle drives previews: it deploys and tears down a pull request's part of its preview, and sweeps every preview of the gitops repo.
Index ¶
- Constants
- Variables
- func FanOutPRComments(ctx context.Context, f forge.Forge, vals preview.PreviewValues, body string) error
- func PRKey(t Target) string
- func Sweep(ctx context.Context, api SweepAPI, now time.Time, ttl time.Duration) error
- type Applier
- type CapCheckError
- type CatchUp
- type CatchUpAPI
- type CatchUpRecorder
- type CatchUpStore
- type DeployAPI
- type DeployResult
- type Event
- type FanOutFunc
- type ReconcileAPI
- type ReconcileFunc
- type ReconcileResult
- type ReconcileStore
- type Recorder
- type SweepAPI
- type SweepStore
- type SyncAPI
- type SyncReport
- type SyncStore
- type Syncer
- type Target
- type TeardownAPI
Constants ¶
const ( // NoServiceReason is the skip reason of a reconcile whose PR changes no // service of its repo: no changed file matches their paths. NoServiceReason = "no service changed" // PreviewLimitReason is the skip reason of a reconcile refused because // creating its preview would exceed preview.maxPreviews. PreviewLimitReason = "preview limit reached" // NotLabeledReason is the skip reason of an opened, reopened or // synchronize event of a PR without a preview label. NotLabeledReason = "not labeled" // OtherLabelReason is the skip reason of a labeled or unlabeled event of // a label that is not a preview label. OtherLabelReason = "other label" // ForkPRReason is the skip reason of a fork PR. ForkPRReason = "fork pr" // RepoNotInCatalogReason is the skip reason of a PR of a repo with no // service in the catalog. RepoNotInCatalogReason = "repo not in catalog" // ServiceHeldReason is the skip reason of a reconcile refused because // another PR pins one of its services in its target preview. ServiceHeldReason = "service held by another pr" // LabelConflictReason is the skip reason of an open PR whose named // preview labels conflict. LabelConflictReason = "conflicting preview labels" )
Skip reasons of a reconcile.
const ( // OutcomeDeployed is the outcome of a reconcile that wrote a service. OutcomeDeployed = "deployed" // OutcomeSkipped is the outcome of a skipped reconcile, with its reason. OutcomeSkipped = "skipped" // OutcomeTornDown is the outcome of a reconcile that only tore down. OutcomeTornDown = "torn_down" // OutcomeFailed is the outcome of a reconcile that failed. OutcomeFailed = "failed" )
Reconcile outcomes, the outcome label of Recorder.Reconcile.
const ( TriggerPush = "push" TriggerAPI = "api" )
Config sync triggers, the trigger attribute of the config sync logs.
const PRClosedReason = "PR closed"
PRClosedReason is the teardown reason for a closed (or merged) PR.
Variables ¶
var ( ErrConfigUnavailable = errors.New("badil.yaml unavailable") // ErrPreviewNotFound is a slug whose preview file does not exist. ErrPreviewNotFound = errors.New("preview not found") )
Errors of Syncer.Sync. Callers test them with errors.Is.
var ErrPreviewLimit = errors.New("preview limit reached")
ErrPreviewLimit is the error of a deploy refused because creating its preview would exceed preview.maxPreviews. Callers test it with errors.Is.
Functions ¶
func FanOutPRComments ¶ added in v0.26.0
func FanOutPRComments(ctx context.Context, f forge.Forge, vals preview.PreviewValues, body string) error
FanOutPRComments posts (or updates) the same markdown body as badil's comment (forge.Forge.UpsertComment) on every open PR referenced in vals.Services.Metadata.pr-url. Closed PRs are skipped, so a stale summary never overwrites their teardown comment. Failures on individual services (including a PR state lookup) are collected but do not abort the loop — best-effort delivery.
func PRKey ¶ added in v0.26.0
PRKey identifies the PR of t: its owner/repo, lowercased as GitHub compares them case-insensitively, and number.
func Sweep ¶
Sweep visits every preview of the gitops repo once, in one sweep operation, applies the first matching rule 1-3, then syncs every preview that rules 1 and 2 did not match (step 4):
- no pinned entry: the preview is deleted;
- ttl > 0 and the newest updated-at of its pinned entries is before now - ttl: the preview is deleted and its open PRs are told it expired;
- otherwise every distinct PR pinning an entry is looked at. A closed one is torn down, its comment saying so. An open one whose labels (preview.ResolveTarget) conflict, or target another preview, is unpinned without a comment; one with no target, pinned outside its branch slug, is torn down with a comment. Other open PRs are left alone.
- after rule 3, the preview is rewritten to match the catalog (store.Tree.Sync). A rewrite is recorded and logged; when it changed the service list or a host, the open PRs' comments are refreshed.
The rules are decided on the tree each attempt of the operation reads. The states of the PRs pinned in the previews are read before the operation, once per distinct PR: a PR whose state can't be read, or that a retried attempt finds pinned without having been read, keeps its pins until the next sweep. The catalog of the tree gives the preview label and step 4; when it can't be read, a warning is logged, only closed PRs are torn down by rule 3 and step 4 is skipped.
A ttl of 0 disables rule 2. A preview that can't be read or synced is logged and counted, and the sweep goes on; Sweep then returns an error carrying the count. A failed comment is only logged. A ListPreviews error, or a failed operation, is returned at once.
The number of listed previews and each rule 1-2 deletion are recorded through the Recorder; teardowns are recorded with the sweep trigger.
Types ¶
type CapCheckError ¶ added in v0.26.0
CapCheckError is the error of a read the preview cap check of DeployPR makes on the tree it writes: Op is "read preview" when the preview could not be read, "list previews" when the previews could not be listed.
func (*CapCheckError) Error ¶ added in v0.26.0
func (e *CapCheckError) Error() string
func (*CapCheckError) Unwrap ¶ added in v0.26.0
func (e *CapCheckError) Unwrap() error
type CatchUp ¶ added in v0.26.0
type CatchUp struct {
// contains filtered or unexported fields
}
CatchUp reconciles the open pull requests that missed their webhooks. It keeps, for the lifetime of the value, the head SHA at which each PR was last reconciled without failing (the seen map) and the PRs whose reconcile is queued or running. Its methods are safe for concurrent use.
func NewCatchUp ¶ added in v0.26.0
func NewCatchUp(api CatchUpAPI, reconcile ReconcileFunc) *CatchUp
NewCatchUp returns a CatchUp over api that reconciles through reconcile, with an empty seen map.
func (*CatchUp) Run ¶ added in v0.26.0
Run lists the open pull requests of every repo of the catalog's services (store.ServiceCatalog.GitHubRepos) and reconciles each one that needs it, decided in this order:
- a PR without a preview label (the plain label, or a named one with a slug) is left alone;
- so is a fork PR (its head repo differs from its base repo). A PR left alone at step 1 or 2 is passed to the Skipped callback, when set, with the time taken just before its repo was listed;
- its target preview is resolved from its labels (preview.ResolveTarget); with conflicting labels it has none, and goes on to step 5;
- a PR with a target whose preview file has an entry whose pr-url names the PR (preview.MatchesPR) and whose commitSha is its head SHA is pinned at head, and skipped;
- a PR in the seen map at its head SHA, or whose catch-up reconcile is queued or running, is skipped;
- any other PR is reconciled as a synchronize event with its listed labels. Once its reconcile completes with an outcome other than failed, it enters the seen map at the head SHA listed here.
A repo whose listing fails is logged and skipped. When the catalog can't be read, Run logs it and lists nothing. Once ctx is done, Run lists no more repos and claims no more PRs. Each started reconcile is recorded, and the run ends with the catch-up log line.
type CatchUpAPI ¶ added in v0.26.0
type CatchUpAPI struct {
Store CatchUpStore
Forge forge.Forge
Recorder CatchUpRecorder
// Skipped, when set, is called with the target of each listed PR that
// Run leaves alone at its step 1 or 2, the skipped result it would get
// (reason NotLabeledReason or ForkPRReason, at its listed head SHA), and
// listedAt, taken just before Run listed the PR's repo.
Skipped func(t Target, res ReconcileResult, listedAt time.Time)
}
CatchUpAPI is what CatchUp uses: the store, the forge, the recorder and, when set, Skipped.
type CatchUpRecorder ¶ added in v0.26.0
type CatchUpRecorder interface {
CatchUpReconcile()
}
CatchUpRecorder records the reconciles catch-up starts. *metrics.Metrics implements it; a nil one records nothing.
type CatchUpStore ¶ added in v0.26.0
type CatchUpStore interface {
FetchServiceCatalog(ctx context.Context) (*store.ServiceCatalog, error)
GetPreview(ctx context.Context, slug string) (*preview.PreviewValues, string, error)
}
CatchUpStore is the subset of store.GitHubStore used by CatchUp.
type DeployAPI ¶
type DeployAPI struct {
Store Applier
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
}
DeployAPI is what DeployPR uses: the store, the forge, the Recorder and the comment fan-out.
type DeployResult ¶ added in v0.26.0
DeployResult is the outcome of DeployPR: the operation's commit, the remote head when the deploy changed nothing.
func DeployPR ¶
func DeployPR( ctx context.Context, api DeployAPI, catalog *store.ServiceCatalog, slug string, inputs preview.DeployInputs, ) (*DeployResult, error, error)
DeployPR pins inputs.ServiceName at inputs.CommitSha in the preview slug, as one deploy operation, then posts the preview summary on every open PR of the preview. The deploy always writes the service, refreshing its updated-at; it is refused with ErrPreviewLimit when the preview does not exist and catalog.MaxPreviews previews already do, a check made on the tree the deploy writes, whose read errors are a *CapCheckError. A deploy that changes nothing (the same inputs within the same second) commits nothing: its result and comments carry the remote head's commit. It returns the result, the fan-out error (possibly joined, nil when every comment landed) and the operation's error; on an error nothing is commented. It does not log.
type Event ¶
type Event struct {
Target
// Action is the webhook action (opened, labeled, ...).
Action string
// HeadRef is the PR's head branch in the payload. Only the payload
// teardown of a closed PR uses it.
HeadRef string
// Label is the added or removed label, on labeled and unlabeled.
Label string
// Labels holds the names of the PR's labels in the payload.
Labels []string
// HeadSHA is the PR's head SHA in the payload, or in the listing of a
// catch-up event.
HeadSHA string
}
Event is a pull_request webhook delivery to reconcile. Its Target's Slug is empty: the slug comes from the PR read from GitHub.
type FanOutFunc ¶ added in v0.26.0
type FanOutFunc func(ctx context.Context, f forge.Forge, vals preview.PreviewValues, body string) error
FanOutFunc posts body on the open PRs of vals through f. FanOutPRComments is the one badil runs.
type ReconcileAPI ¶
type ReconcileAPI struct {
Store ReconcileStore
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
}
ReconcileAPI is what ReconcilePR uses: the store, the forge, the Recorder and the comment fan-out.
type ReconcileFunc ¶ added in v0.26.0
type ReconcileFunc func(ctx context.Context, ev Event, done func(ReconcileResult))
ReconcileFunc reconciles ev, as ReconcilePR does, and calls done with ReconcilePR's result once the reconcile completes. It may return before. A reconcile that panics calls done with the failed outcome, or its PR stays queued for the lifetime of the CatchUp.
type ReconcileResult ¶ added in v0.26.0
ReconcileResult is the outcome ReconcilePR records, the reason when it is skipped ("" otherwise), and the head SHA of the PR it reconciled: the one GetPullRequest read when that read succeeded, else the event's.
func ReconcilePR ¶
func ReconcilePR(ctx context.Context, api ReconcileAPI, ev Event) ReconcileResult
ReconcilePR brings the preview in line with the PR's current state on GitHub. When the payload shows the event cannot concern a preview label, nothing is read. Otherwise the PR is read and its labels resolve its target preview (preview.ResolveTarget). The PR is first torn down from every other preview it may still be pinned in. Then, when it is open and has a target, the catalog services of its repo that it touches (touchedServices) are deployed there at its head SHA, unless another PR already pins one of them, or the preview does not exist and preview.maxPreviews previews already do; before that deploy, the PR's entries there for the other services of its repo are unpinned. A PR that touches no service is torn down from its target and told so, and the reconcile is skipped. An open PR with conflicting named labels is told so. Fork PRs and repos outside the catalog are skipped. Every outcome is logged.
The forge is read first. The teardowns and the deploy are then one operation of the store, one commit, decided on the tree each push attempt reads (reconcilePlan.change): a deploy operation when the PR is open with a target, a teardown otherwise. The comments are posted once it is pushed.
A closed event is not guarded by its payload nor skipped for a repo outside the catalog, and a closed fork PR is still torn down. When the catalog or the PR can't be read, it falls back to tearing down the payload's head branch and named labels as closed.
A service already deployed as it would be written (only its updated-at would change) is not written nor commented again, unless the cleanup removed the PR from another preview. When every service is, the reconcile is skipped as already deployed.
Each call records exactly one outcome through the Recorder: failed when the catalog or the PR can't be read on a non-closed event, when the PR's files can't be listed, the target preview can't be read or the previews can't be listed (the teardowns from the PR's other previews are still committed), or when the commit of a PR open with a target can't be pushed; otherwise skipped (with its reason) when the reconcile was skipped; otherwise deployed when a service was written; otherwise torn_down. It returns that outcome and reason, with the head SHA of the PR it read, or ev's when it read none.
type ReconcileStore ¶ added in v0.26.0
type ReconcileStore interface {
Applier
FetchServiceCatalog(ctx context.Context) (*store.ServiceCatalog, error)
}
ReconcileStore is the subset of store.GitHubStore used by ReconcilePR.
type Recorder ¶
type Recorder interface {
// Reconcile records one ReconcilePR outcome and, when skipped, its reason.
Reconcile(outcome, reason string)
// Teardown records one teardown of a PR from a preview.
Teardown(trigger, result string)
// SweepListed records the number of previews a sweep listed.
SweepListed(n int)
// SweepDeleted records one preview deleted by a sweep rule.
SweepDeleted(rule string)
// PreviewSynced records one preview rewritten to match badil.yaml.
PreviewSynced()
// PreviewCreated records one preview a deploy created.
PreviewCreated()
}
Recorder records lifecycle outcomes. *metrics.Metrics implements it; a nil one records nothing.
type SweepAPI ¶
type SweepAPI struct {
Store SweepStore
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
}
SweepAPI is what Sweep uses: the store, the forge, the Recorder and the comment fan-out.
type SweepStore ¶ added in v0.26.0
type SweepStore interface {
Applier
ListPreviews(ctx context.Context) ([]string, error)
GetPreview(ctx context.Context, slug string) (*preview.PreviewValues, string, error)
}
SweepStore is the subset of store.GitHubStore used by Sweep.
type SyncAPI ¶ added in v0.21.0
type SyncAPI struct {
Store SyncStore
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
}
SyncAPI is what Syncer uses: the store, the forge, the Recorder and the comment fan-out.
type SyncReport ¶ added in v0.21.0
SyncReport is the outcome of a run: the slugs rewritten, the number of previews left unchanged and the slugs that failed, in listing order.
type SyncStore ¶ added in v0.26.0
type SyncStore interface {
Applier
FetchServiceCatalogSHA(ctx context.Context) (*store.ServiceCatalog, string, error)
}
SyncStore is the subset of store.GitHubStore used by Syncer.
type Syncer ¶ added in v0.21.0
type Syncer struct {
// contains filtered or unexported fields
}
Syncer runs the sweep's sync step (store.Tree.Sync) over every preview, or one, outside the sweep, as one sync operation. One guarded run happens at a time in the process: a push run (Push) or an API run (Sync), each waiting for the guard in turn. Waiters acquire the guard in no particular order. Each run is capped at timeout from when it holds the guard.
func NewSyncer ¶ added in v0.21.0
NewSyncer returns a Syncer over api whose runs are capped at timeout.
func (*Syncer) Push ¶ added in v0.21.0
Push runs the sync of a push to the gitops default branch. Holding the guard, it reads badil.yaml's blob SHA and stops when it equals the SHA the last push run synced: a push queued behind the run that synced its content does nothing more. Otherwise every preview is synced with the catalog of that content and the SHA recorded, also when a preview failed (the sweep retries it) or the content can't be parsed (the same content would fail again). A badil.yaml that can't be read, or a failed sync operation, record nothing, so the next push retries.
func (*Syncer) Sync ¶ added in v0.21.0
Sync runs an API sync: every preview when slug is "", else the preview slug, which the caller has validated. It waits for the guard until ctx is done. It returns an error wrapping ErrConfigUnavailable when badil.yaml can't be read or parsed, ErrPreviewNotFound when slug has no preview file, the operation's error when the sync operation fails, or ctx's error when it was done before the guard was free. A preview that can't be synced is in the report, not an error. It never reads nor changes the SHA of the push runs.
type TeardownAPI ¶
type TeardownAPI struct {
Store Applier
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
}
TeardownAPI is what a teardown uses: the store, the forge, the Recorder and the comment fan-out.