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.Values, 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 ExpiryStore
- type FanOutFunc
- type NamespaceCheckError
- type NamespaceChecker
- type Op
- type ReconcileAPI
- type ReconcileFunc
- type ReconcileResult
- type ReconcileStore
- type Recorder
- type Result
- type Summary
- type SweepAPI
- type SweepStore
- type SyncAPI
- type SyncReport
- type SyncResult
- type SyncStore
- type Syncer
- type Target
- type TeardownAPI
- type TeardownResult
- type Tree
- type WriteResult
Constants ¶
const ( OpDeploy = "deploy" OpTeardown = "teardown" OpSweep = "sweep" OpSync = "sync" )
Operation kinds, the op label of an Apply's duration and push conflicts.
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" // NamespaceInUseReason is the skip reason of a reconcile refused because // the namespace of its new preview exists and is not a preview namespace // for its slug. NamespaceInUseReason = "namespace in use" // 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 ErrNamespaceInUse = errors.New("namespace in use")
ErrNamespaceInUse is the error of a deploy refused because the namespace of its new preview exists and is not a preview namespace for its slug. Callers test it with errors.Is.
var ErrNotFound = errors.New("gitops: not found")
ErrNotFound is returned when a file of the gitops repo does not exist. Callers should test 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.
ErrUnauthorized is returned when the gitops remote refused the credentials. Callers should test with errors.Is.
Functions ¶
func FanOutPRComments ¶ added in v0.26.0
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, parsed with f.ParsePRURL. 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, its open PRs are recorded in api.Expiry at their head SHA, when set, and 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 (syncPreview). 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 (catalog.Catalog.Repos, by the forge's repo URL rule) 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;
- a PR the expiry store (api.Expiry) holds at its head SHA, which the sweep expired for the TTL, is skipped; one it holds at another SHA has its record cleared and goes on. A failed read is logged and the PR goes on;
- its target preview is resolved from its labels (preview.ResolveTarget); with conflicting labels it has none, and goes on to step 6;
- 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. Before the catch-up log line that ends the run, the expiry store is pruned (pruneExpiry).
type CatchUpAPI ¶ added in v0.26.0
type CatchUpAPI struct {
Store CatchUpStore
Forge forge.Forge
Recorder CatchUpRecorder
// Expiry, when set, holds the PRs the sweep expired, which Run skips at
// the head SHA they were expired at.
Expiry ExpiryStore
// 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, the expiry store and 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) (*catalog.Catalog, error)
GetPreview(ctx context.Context, slug string) (*preview.Values, 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
Namespaces NamespaceChecker
Expiry ExpiryStore
}
DeployAPI is what DeployPR uses: the store, the forge, the Recorder, the comment fan-out, the namespace check of a new preview (nil checks nothing) and the expiry store (nil clears nothing).
type DeployResult ¶ added in v0.26.0
type DeployResult struct {
Commit Result
}
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 *catalog.Catalog, 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. Otherwise, when the preview does not exist, it is refused with ErrNamespaceInUse when its namespace exists and is not a preview namespace for slug (api.Namespaces); a failed check is a *NamespaceCheckError. A deploy that changes nothing (the same inputs within the same second) commits nothing: its result and comments carry the remote head's commit. A deploy that is not refused clears the expiry record of the PR inputs.PRURL names (api.Expiry). 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 logs only the warnings expiry clear failed, when the record can't be cleared, and expiry clear skipped, when inputs.PRURL does not parse.
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 ExpiryStore ¶ added in v0.30.2
type ExpiryStore interface {
// Mark records key (a PRKey) as expired at headSHA, replacing any record of key.
Mark(ctx context.Context, key, prURL, headSHA string, at time.Time) error
// Recorded returns the head SHA key is recorded at; ok is false when key has no record.
Recorded(ctx context.Context, key string) (headSHA string, ok bool, err error)
// Clear removes the record of key; a missing record is no error.
Clear(ctx context.Context, key string) error
// Prune removes every record whose key keep returns false for.
Prune(ctx context.Context, keep func(key string) bool) error
}
ExpiryStore remembers the open PRs of the previews the sweep deleted for the TTL, each at the head SHA it had then, so that catch-up does not deploy them again until they get a new head or are deployed by a label event or /v1/deploy. Keys are PRKey values. A nil ExpiryStore in an API struct remembers nothing.
type FanOutFunc ¶ added in v0.26.0
FanOutFunc posts body on the open PRs of vals through f. FanOutPRComments is the one badil runs.
type NamespaceCheckError ¶ added in v0.28.0
type NamespaceCheckError struct {
Err error
}
NamespaceCheckError is the error of a failed namespace check of a new preview (NamespaceChecker.Foreign).
func (*NamespaceCheckError) Error ¶ added in v0.28.0
func (e *NamespaceCheckError) Error() string
func (*NamespaceCheckError) Unwrap ¶ added in v0.28.0
func (e *NamespaceCheckError) Unwrap() error
type NamespaceChecker ¶ added in v0.30.0
type NamespaceChecker interface {
// Foreign reports whether the namespace name exists and is not a preview
// namespace for the slug name: one labelled badil.dev/preview=<name>. A
// failed read is returned.
Foreign(ctx context.Context, name string) (bool, error)
}
NamespaceChecker reads the namespace of a new preview.
type Op ¶ added in v0.30.0
Op is one write to the gitops repo. Kind is OpDeploy, OpTeardown, OpSweep or OpSync. Change reads the tree of the remote head and puts or deletes its files through it; it may run several times, once per attempt, so it reads nothing but tree and has no other side effect. An error from Change fails the operation with nothing committed.
type ReconcileAPI ¶
type ReconcileAPI struct {
Store ReconcileStore
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
Namespaces NamespaceChecker
// Expiry, when set, loses the record of a PR once a reconcile deploys it.
Expiry ExpiryStore
}
ReconcileAPI is what ReconcilePR uses: the store, the forge, the Recorder, the comment fan-out and the namespace check of a new preview (nil checks nothing).
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, or the preview does not exist and its namespace exists and is not a preview namespace for its slug (NamespaceChecker); 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, the previews can't be listed or the target's namespace can't be checked (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) (*catalog.Catalog, 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 Result ¶ added in v0.30.0
Result is the outcome of a successful Apply. NoOp is true when the last attempt's Change changed nothing: nothing was committed, and Commit is the remote head it ran on. Otherwise Commit is the pushed commit. Subject is Commit's subject line, URL its GitHub URL. Deleted holds the sorted slugs of the previews whose previews/<slug>/values.yaml the pushed commit deleted, empty when none.
type Summary ¶ added in v0.30.0
type Summary struct {
Subject string
}
Summary describes the change an operation made: the subject of its commit.
type SweepAPI ¶
type SweepAPI struct {
Store SweepStore
Forge forge.Forge
Recorder Recorder
FanOut FanOutFunc
// Expiry, when set, records the open PRs of the previews rule 2 deletes.
Expiry ExpiryStore
}
SweepAPI is what Sweep uses: the store, the forge, the Recorder, the comment fan-out and, when set, the expiry store.
type SweepStore ¶ added in v0.26.0
type SweepStore interface {
Applier
ListPreviews(ctx context.Context) ([]string, error)
GetPreview(ctx context.Context, slug string) (*preview.Values, 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 SyncResult ¶ added in v0.30.0
type SyncResult struct {
Values preview.Values
Excluded []string
Changed bool
Notify bool
NotFound bool
}
SyncResult is the outcome of syncPreview. Changed is true when the file was rewritten; Values and Excluded (preview.Projection.Excluded) then describe it. Notify is true when the rewritten file's ordered list of service or dependency names, or any entry's host, differs from the file it replaced. NotFound is true when the file does not exist.
type SyncStore ¶ added in v0.26.0
type SyncStore interface {
Applier
FetchServiceCatalogSHA(ctx context.Context) (*catalog.Catalog, 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 (syncPreview) 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.
type TeardownResult ¶ added in v0.30.0
type TeardownResult struct {
Values preview.Values
Excluded []string
Catalog *catalog.Catalog
Removed []string
Deleted bool
}
TeardownResult is the outcome of teardownPreview and unpinPreviewServices. Removed lists the services unpinned from the PR; it is empty when there was nothing to tear down. Values, Excluded (preview.Projection.Excluded) and Catalog, the badil.yaml the file was projected on, are set only when Deleted is false.
type Tree ¶ added in v0.30.0
type Tree interface {
// Catalog returns the service catalog of the tree's badil.yaml.
Catalog() (*catalog.Catalog, error)
// ListPreviews returns the sorted names of the directories under
// previews/, with the operation's changes: a preview whose last file was
// deleted is gone, one whose file was put is there.
ListPreviews() ([]string, error)
// GetPreview returns the parsed previews/<slug>/values.yaml, ErrNotFound
// when it does not exist.
GetPreview(slug string) (*preview.Values, error)
// PutPreview puts vals at previews/<slug>/values.yaml. It records
// nothing.
PutPreview(slug string, vals preview.Values) error
// DeletePreview deletes previews/<slug>/values.yaml, recorded as
// "delete". The preview must exist.
DeletePreview(slug string)
// Record adds change to the commit body lines of the preview slug.
Record(slug, change string)
// GitopsRepoURL returns the gitops repo URL the tree's previews are
// projected with: the gitopsRepoURL of their files.
GitopsRepoURL() string
}
Tree is what an operation of Apply reads and changes: the gitops repo at the fetched remote head, plus the preview files the operation put or deleted so far. Its reads see those changes.
type WriteResult ¶ added in v0.30.0
WriteResult is the outcome of deployPreview. Unchanged is true when skipUnchanged left the file as it was: Values then holds that file. Created is true when the deploy created the file. Excluded is the projection's (preview.Projection.Excluded).