officership

package
v0.166.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package officership is what lets an officer SHIP: push branches, merge its own pull requests and tag releases in one repository, with every write decided in muster-server (docs/officers.md "Shipping officers").

  • pushgate.go: the connector-proxy write filter (a connectors.Gate) an instance's every GitHub request passes through;
  • gates.go: officer_merge_pr's and officer_tag_release's gates, all read fresh from GitHub and HQ at call time;
  • lint.go: the destructive-DDL lint on migration files;
  • rollout.go: the post-release watch and the automatic rollback.

🔴 THE REPOSITORY ENFORCES NOTHING, SO THIS PACKAGE IS THE BRANCH PROTECTION. A private repository on a plan without branch protection or rulesets lets any `contents: write` token push to its base branch, push any tag and merge with red checks. The officer's write token therefore never leaves muster: the instance's requests reach GitHub only through the push gate, and merges and tags are made here, after the gates, with muster's own token.

Index

Constants

View Source
const (
	CIStateNoRun     = "no_run"
	CIStateRunning   = "running"
	CIStateSucceeded = "succeeded"
	CIStateFailed    = "failed"
)

CIRunState is a PipelineRun's state as officer_ci_logs reports it.

View Source
const (
	GateStage      = "stage"
	GateHQEnabled  = "hq_enabled"
	GatePR         = "pull_request"
	GateBase       = "base"
	GateHeadBranch = "head_branch"
	GateAuthor     = "author"
	GateMergeable  = "mergeable"
	GateUpToDate   = "up_to_date"
	GateChecks     = "checks"
	GateReview     = "review"
	GateHold       = "hold"
	GateMigrations = "migrations"
	GateNotice     = "notice"
	GateMerge      = "merge"
	// GateReady is officer_mark_ready's write: GitHub's draft -> ready
	// conversion.
	GateReady      = "ready"
	GateTags       = "tags"
	GateAncestor   = "ancestor"
	GateInFlight   = "in_flight"
	GateRate       = "rate"
	GateQuietHours = "quiet_hours"
	GateMainCI     = "main_ci"
	GateBackup     = "backup"
	GateTagCreate  = "tag_create"
	// GateUntestedMerge refuses a release while the base's head is an
	// officer merge that raced the base (MergeOutcome.UntestedTree).
	GateUntestedMerge = "untested_merge"
)

Gate names, as a refusal and the call log name them.

View Source
const (
	VerdictWatching   = "watching"
	VerdictHealthy    = "healthy"
	VerdictNotLive    = "not_live"
	VerdictUnhealthy  = "unhealthy"
	VerdictSuperseded = "superseded"
	VerdictAborted    = "aborted"
)

Watch verdicts.

View Source
const DefaultCreateWait = 2 * time.Minute

DefaultCreateWait is how long a create waits for the officer's previous one to finish before it is refused.

View Source
const GateCIRuns = "ci_runs"

GateCIRuns is officer_ci_logs's cluster gate (besides GatePR, GateHeadBranch, GateAuthor).

View Source
const SweepInterval = 5 * time.Minute

SweepInterval is how often the draft sweep (Sweep) re-checks every open pull request of a draft officer.

Variables

View Source
var ErrMergeConflict = errors.New("officership: merge conflict")

ErrMergeConflict is a merge GitHub could not make cleanly (409).

View Source
var ErrRefExists = errors.New("officership: the ref already exists")

ErrRefExists is a create of a ref that already exists (GitHub's 422): the compare-and-swap against a concurrent tag or branch.

Functions

func BotLogin

func BotLogin(slug string) string

BotLogin is a GitHub App's bot account login.

func Excerpt added in v0.125.0

func Excerpt(log string, maxBytes int) (string, bool)

Excerpt reduces a CI log to what explains its failure — the failing-test and error lines (deduplicated, in order, repeats counted), then the log's last lines — every line passed through RedactLines and cut at maxExcerptLine bytes, the whole at most maxBytes bytes (never splitting a character). cut reports that the cap dropped something or an emitted line was clipped.

func ForbiddenFiles added in v0.156.0

func ForbiddenFiles(forbidden []string, files []File) ([]string, string)

ForbiddenFiles is THE content rule of a draft officer's comparison: the paths that make it refused and why (none: admitted). A file is refused when

  • its path or its old path matches a forbidden glob;
  • it is a .gitattributes file, in any directory, added, modified, removed or renamed (one can mark manifests -diff or binary, and GitHub then shows their changes as no diff);
  • GitHub shows no diff for it (an empty patch): a binary file (GitHub reports changes 0), a large file (changes > 0), a pure rename or copy, a mode change — none can be checked. The one exception is a REMOVED file with changes 0 (a binary or empty file — or a manifest an attribute made look like one), which passes HERE and is judged by checkComparison from its content at the merge base (removedNoDiffWhy); its path rule still applies;
  • a removed line declares a PersistentVolumeClaim, a PersistentVolume, a CloudNativePG resource or a Flagger Canary (removedKindRE);
  • an added line is a kustomize `$patch: delete` (whatever it targets: its kind may sit outside the hunk);
  • a removed `name:` line in a diff that shows a protected kind (renaming a volume, database or canary deletes it and creates another);
  • an added line has a secret-shaped value (redact.HasSecretLiteralIn, which judges a credential-like KEY as well as a value), or one YAML mapping's credential-like name: has a literal value: (an env entry, a JSON6902 env add, a flow mapping; redact.HasSecretPairIn, judged on each hunk's post-image WITH its context lines, so an unchanged name line counts and a pair is never made across two entries);
  • an added kind: Secret holds a literal data/stringData value (plainSecret).

⚠ BEST EFFORT, BY THE DIFF: a hunk shows three lines of context, so a rule that needs the document's kind sees it only when the hunk does. The kustomization rule (an entry dropped from resources:) needs the base, and is checkComparison's. The deletion rules are an early refusal; the wall is the target repository's render-diff CI gate (removedKindRE).

func IsRollbackTag

func IsRollbackTag(message string) bool

IsRollbackTag reports whether an annotated tag's message carries the rollback trailer (a whole line, exactly).

func NewKubeCIOpener added in v0.125.0

func NewKubeCIOpener(ns, sa string) (func(ctx context.Context) (CIReader, error), error)

NewKubeCIOpener builds the production CILogsReader.Open for the CI namespace ns: each call mints a 600 s token for ServiceAccount sa in muster's OWN namespace (TokenRequest, with muster's own in-cluster identity, which may create serviceaccounts/token for sa only) and returns a reader authenticated by that token alone.

🔴 muster's own token MINTS; it never READS. The reader's config is built fresh (ciReaderConfig), so nothing of muster's credentials — its token file above all, which client-go would prefer over the minted token — reaches it.

func OrphanNotice added in v0.156.0

func OrphanNotice(officerID, channel string, orphans []Orphan) officers.Notice

OrphanNotice is the HQ notice of a non-empty orphan report: the repository:branch list, and what to do with it.

func Redact added in v0.125.0

func Redact(line string) string

Redact is the one-line filter (RedactLines applies it to every line outside a PEM block): a line that looks like it carries a credential, or is an environment assignment, is withheld whole; a URL's userinfo is masked.

func RedactCutTail added in v0.127.0

func RedactCutTail(s string, known []string) string

RedactCutTail withholds every line in which a word cut by a cap — the word right before a cutMark — could be a credential's prefix: it starts like a known token shape (cutPrefixRE), or it ends in the first 4 or more bytes of one of known (a credential the caller holds and can name). A shape pattern needs the whole token; a cap can leave only its start, and that start is still the credential's.

func RedactLines added in v0.125.0

func RedactLines(lines []string) []string

RedactLines is THE secret filter of a CI log, line by line WITH STATE: a PEM block is withheld whole, from its BEGIN line through its END line (to the end of the log when END never came — a step that died mid-print); every other line goes through Redact, and a bare long base64 line is withheld.

func RedactText added in v0.127.0

func RedactText(s string) string

RedactText is THE CI-log secret filter (RedactLines, unchanged) over any multi-line text — an officer's session transcript forwarded to HQ (internal/officers/transcript) — split at the same separators as a log (\n, \r\n, a lone \r) but KEEPING empty lines, so prose keeps its paragraphs. Every line is joined back with \n.

func SensitiveFiles

func SensitiveFiles(patterns []string, files []File) []string

SensitiveFiles are the changed paths (a rename's old path included) that match any pattern, sorted and unique.

Types

type Branch added in v0.156.0

type Branch struct {
	Name string
	SHA  string
}

Branch is one branch: its name (without refs/heads/) and head commit.

type CILogsOutcome added in v0.125.0

type CILogsOutcome struct {
	PR      int    `json:"pr"`
	HeadSHA string `json:"head_sha"`
	// PipelineRun is the run read (the newest for the head); OtherRuns is how
	// many older runs for the same head were ignored.
	PipelineRun string `json:"pipeline_run,omitempty"`
	OtherRuns   int    `json:"other_runs_for_this_head,omitempty"`
	State       string `json:"state"`
	RunMessage  string `json:"run_message,omitempty"`
	// Failed are the failed tasks, each with its excerpt.
	Failed []TaskFailure `json:"failed_tasks"`
	// Note says, in words, what was found — never empty.
	Note string `json:"note"`
}

CILogsOutcome is officer_ci_logs's answer.

type CILogsReader added in v0.125.0

type CILogsReader struct {
	Repo   string
	Ship   *officers.Ship
	Config *officers.CILogs
	GH     GitHub
	// Open returns a reader for ONE call — in production with a freshly
	// minted token ([NewKubeCIOpener]). It is called only once ownership
	// passed, and at most once per call.
	Open func(ctx context.Context) (CIReader, error)
}

CILogsReader answers officer_ci_logs for one officer. Its caller (internal/api) builds it only for an officer with a ship and ci_logs block.

func (*CILogsReader) Read added in v0.125.0

func (r *CILogsReader) Read(ctx context.Context, n int) (CILogsOutcome, error)

Read answers officer_ci_logs{pr}.

type CIReader added in v0.125.0

type CIReader interface {
	// PipelineRuns lists the PipelineRuns matching a label selector.
	PipelineRuns(ctx context.Context, selector string) ([]PipelineRun, error)
	// TaskRuns lists the TaskRuns of one PipelineRun.
	TaskRuns(ctx context.Context, pipelineRun string) ([]TaskRun, error)
	// PodLog reads the END of one container's log: at most its last
	// maxBytes bytes (and last tailLogLines lines); cut reports that anything
	// before that was dropped.
	PodLog(ctx context.Context, pod, container string, maxBytes int64) (log string, cut bool, err error)
}

CIReader is every cluster read officer_ci_logs makes, in ONE namespace (the implementation is bound to it). The production one is [NewKubeCIReader]; the tests use a fake.

type CheckRun

type CheckRun struct {
	ID         int64
	Name       string
	Status     string
	Conclusion string
	AppSlug    string
}

CheckRun is one check run on a commit.

type Comment

type Comment struct {
	Author     string
	AuthorType string // User | Bot | Organization
	Body       string
}

Comment is any human-or-bot text on a pull request: a conversation comment, a review body or a review comment.

type Compare

type Compare struct {
	Status   string // ahead | behind | diverged | identical
	AheadBy  int
	BehindBy int
	Files    []File
	Commits  []string // shas, oldest first
	// MergeBase is the comparison's merge base commit: what a removed file
	// is read at when GitHub shows no diff for it (the draft gate).
	MergeBase string
}

Compare is GET compare/{base}...{head}.

type File

type File struct {
	Path     string
	Previous string // a rename's old path
	Status   string // added | modified | removed | renamed | copied | changed | unchanged
	// Patch is the file's unified diff hunks as GitHub reports them, and
	// Changes its added+removed line count. GitHub OMITS the patch of a binary
	// file (reported with changes 0, MEASURED on a read-only comparison: every
	// added, modified and removed PNG came back changes 0, additions 0,
	// deletions 0, no patch), of a very large one (changes > 0), and of a pure
	// rename or mode change. An empty Patch is therefore a diff nobody can
	// read whatever Changes says (the draft gate's ForbiddenFiles).
	Patch   string
	Changes int
}

File is one changed file of a pull request or a comparison.

type Finding

type Finding struct {
	File string
	Rule string
	Text string // the normalised statement, bounded
}

Finding is one destructive statement in a migration file.

func LintMigration

func LintMigration(file, sql string) []Finding

LintMigration returns every destructive statement in one migration file. An empty result is a pass.

type Gates

type Gates struct {
	OfficerID string
	Repo      string
	Ship      *officers.Ship
	GH        GitHub
	HQ        HQ
	Now       func() time.Time
	// InFlight reports a release the rollout watch still owns (its tag).
	InFlight func() (string, bool)
	// LiveVersion reads the version the service reports now (the rollout's
	// health URL).
	LiveVersion func(ctx context.Context) (string, error)
	// contains filtered or unexported fields
}

Gates are officer_merge_pr's and officer_tag_release's checks for one officer. Every input is read from GitHub and HQ at call time; nothing is cached between calls.

func (*Gates) MarkReady added in v0.123.0

func (g *Gates) MarkReady(ctx context.Context, n int) (ReadyOutcome, error)

MarkReady converts the officer's own DRAFT pull request n to ready for review — the one draft transition an officer may make. A shipping officer opens test-first pull requests as drafts (the red-before commit must not look reviewable); once CI is green it marks the pull request ready so the review check runs, which officer_merge_pr then requires.

The gates, in order, read fresh:

  1. pull_request — open, not merged, and a draft (an already-ready one is refused: there is no ready -> draft here, and no no-op write);
  2. base / head_branch / author — the officer's own ([Gates.ownPR]);
  3. ready — GitHub's GraphQL markPullRequestReadyForReview on the node id read in 1.

No stage gate (a shadow officer's pull requests are reviewed too) and no HQ gate: this is an edit of the officer's own pull request, which the push gate already forwards (title, body, state) without either. GitHub's REST PATCH pulls takes no `draft` field, which is why this is a tool and not a push-gate rule.

func (*Gates) MergePR

func (g *Gates) MergePR(ctx context.Context, n int) (MergeOutcome, error)

MergePR squash-merges the officer's own pull request n if, and only if, every merge gate passes now. A refusal is a *Refusal naming the gate; on a refusal nothing was written (a sensitive-path notice may have been posted only when every OTHER gate had passed).

The gates, in order:

  1. stage — the officer's stage allows merging;
  2. hq_enabled — HQ answers and says the officer is enabled (fail closed);
  3. base / head_branch / author — open, not draft, into the base branch, from <prefix>… in the same repository, authored by the officer App's bot;
  4. mergeable — GitHub says mergeable (unknown is "call again");
  5. up_to_date — the head contains the base's head (behind_by 0);
  6. checks — every required check is success on the head commit (a commit status, or a completed check run);
  7. review — the newest review check run on the head is completed+success (neutral fails; from review_app when set);
  8. hold — no human wrote /hold on the pull request;
  9. migrations — no destructive DDL in an added or changed migration, and no migration removed or renamed;
  10. notice — if a sensitive path changed, HQ accepted the notice;
  11. merge — GitHub squash-merges with the head pinned to the checked sha.

func (*Gates) TagRelease

func (g *Gates) TagRelease(ctx context.Context, opt TagOptions) (TagOutcome, error)

TagRelease creates the next minor release tag (annotated) on the base branch's head if, and only if, every release gate passes now:

  1. stage — the officer's stage allows releasing;
  2. hq_enabled — HQ says the officer is enabled (fail closed);
  3. tags / ancestor — the highest vX.Y.Z tag T is an ancestor of the base's head H, and H is ahead of it (else nothing to release);
  4. in_flight — no release the rollout watch still owns, and the service reports T's version (the previous release is live);
  5. rate — fewer than releases_per_day officer tags in the last 24 h, and none in the last min_release_gap;
  6. quiet_hours — not inside them;
  7. main_ci — the required checks are success for H's exact tree;
  8. migrations / backup — no destructive DDL in a migration added in T..H, and, when one was added, HQ's backup preflight passes;
  9. tag_create — GitHub creates refs/tags/<next>; a tag pushed by someone else first makes this fail, and the tool reports it.

type GitHub

type GitHub interface {
	AppSlug(ctx context.Context) (string, error)
	PR(ctx context.Context, n int) (PR, error)
	PRFiles(ctx context.Context, n int) ([]File, error)
	Compare(ctx context.Context, base, head string) (Compare, error)
	// Statuses is the latest commit status per context on sha.
	Statuses(ctx context.Context, sha string) (map[string]string, error)
	CheckRuns(ctx context.Context, sha, name string) ([]CheckRun, error)
	PRComments(ctx context.Context, n int) ([]Comment, error)
	FileAt(ctx context.Context, path, ref string) ([]byte, error)
	BranchSHA(ctx context.Context, branch string) (string, error)
	Tags(ctx context.Context) ([]TagRef, error)
	TagObject(ctx context.Context, sha string) (TagObject, error)
	// Commit is a commit's tree and parents.
	Commit(ctx context.Context, sha string) (tree string, parents []string, err error)
	PRsForCommit(ctx context.Context, sha string) ([]PR, error)
	Merge(ctx context.Context, n int, sha string) (string, error)
	CreateTag(ctx context.Context, name, message, sha string, t Tagger) (string, error)
	CreateRef(ctx context.Context, ref, sha string) error
	CreateCommit(ctx context.Context, message, tree string, parents []string) (string, error)
	MergeInto(ctx context.Context, base, head, message string) (string, error)
	OpenPR(ctx context.Context, title, head, base, body string) (int, error)
	// PRsForBranch is every pull request whose head is branch in this
	// repository (GitHub's head=<owner>:<branch> filter, which finds a closed
	// pull request whose branch was deleted too), in state "open", "closed"
	// or "all". Every page is read; more than maxPages pages is an error,
	// never a truncated answer.
	PRsForBranch(ctx context.Context, branch, state string) ([]PR, error)
	// OfficerPRs is every pull request login opened in this repository
	// (GitHub's issues list filtered by creator, every page, newest created
	// first), in state "open", "closed" or "all", with its Body. More than
	// maxPages pages is an error, never a truncated answer.
	OfficerPRs(ctx context.Context, login, state string) ([]PR, error)
	// DeleteBranch deletes refs/heads/<branch> (the draft gate, after it
	// closed a pull request whose branch holds a refused change).
	DeleteBranch(ctx context.Context, branch string) error
	// Branches is every branch whose name starts with prefix.
	Branches(ctx context.Context, prefix string) ([]Branch, error)
	// CommitTime is sha's committer date.
	CommitTime(ctx context.Context, sha string) (time.Time, error)
	// MarkReady converts draft pull request n (GraphQL node nodeID) to ready
	// for review. 🔴 REST cannot: PATCH pulls takes no `draft` field (only
	// POST pulls does), so this is the GraphQL markPullRequestReadyForReview
	// mutation, and it errs unless GitHub answers pull request n, not a draft.
	MarkReady(ctx context.Context, n int, nodeID string) error
	// ClosePR closes pull request n (PATCH pulls/<n> state "closed"): the
	// draft gate's answer to a push that put a refused change into an open
	// pull request.
	ClosePR(ctx context.Context, n int) error
}

GitHub is every GitHub read and write the gates and the watcher make, for ONE repository. The REST implementation is REST; the tests use a fake.

type HQ

type HQ interface {
	// Enabled is HQ's on/off switch for the officer (GET /officers/{id}).
	Enabled(ctx context.Context) (bool, error)
	// PostNotice posts the sensitive-path notice (POST to path under hq_url).
	PostNotice(ctx context.Context, path string, n officers.Notice) error
	// Preflight is HQ's database backup health (POST /officers/{id}/preflight).
	Preflight(ctx context.Context) (officers.Preflight, error)
}

HQ is what the gates ask HQ, with the officer's own token.

type MergeOutcome

type MergeOutcome struct {
	PR       int      `json:"pr"`
	HeadSHA  string   `json:"head_sha"`
	MergeSHA string   `json:"merge_sha"`
	Passed   []string `json:"gates_passed"`
	Noticed  []string `json:"sensitive_paths_noticed,omitempty"`
	// UntestedTree: the merge landed on a base that moved after the gates
	// read it, so the base now holds a tree no CI run saw (Warning says so).
	UntestedTree bool   `json:"untested_tree,omitempty"`
	Warning      string `json:"warning,omitempty"`
}

MergeOutcome is what officer_merge_pr did.

type Orphan added in v0.156.0

type Orphan struct {
	Repo   string    `json:"repo"`
	Branch string    `json:"branch"`
	SHA    string    `json:"sha"`
	Since  time.Time `json:"since"`
}

Orphan is an officer branch no pull request was ever opened from (a refused pull request leaves one), older than officers.OrphanBranchAge.

func OrphanBranches added in v0.156.0

func OrphanBranches(ctx context.Context, officerID, primary string, ship *officers.Ship, ghFor func(string) GitHub, now time.Time) ([]Orphan, error)

OrphanBranches is the daily orphan report of a draft officer: every branch under each ship repository's prefix and the officer's slug that has no pull request in any state, whose head commit is older than officers.OrphanBranchAge at now (each branch's pull requests found by the branch, GitHub's head filter, never in a newest-N window). 🔴 IT ONLY LISTS: nothing here deletes a branch, and the push gate refuses a draft officer's branch deletion. (muster deletes a branch only after closing its pull request on a content hit: draftgate.go closeOnHit.) ghFor is the GitHub of each repository (PushGate.ghFor).

type PR

type PR struct {
	Number         int
	NodeID         string // the GraphQL id (officer_mark_ready's mutation names it)
	State          string
	Draft          bool
	Merged         bool
	Mergeable      *bool
	Author         string
	AuthorType     string
	HeadRef        string
	HeadSHA        string
	HeadRepo       string
	BaseRef        string
	BaseRepo       string
	Title          string
	MergeCommitSHA string
	CreatedAt      time.Time
	// Body is the pull request's description (OfficerPRs fills it: the draft
	// gate reads its item from the first line).
	Body string
}

PR is the part of a pull request the gates read.

type PipelineRun added in v0.125.0

type PipelineRun struct {
	Name    string
	Created time.Time
	Labels  map[string]string
	Params  map[string]string
	// Succeeded is the Succeeded condition's status: True, False or Unknown
	// ("" when there is none yet).
	Succeeded string
	Reason    string
	Message   string
}

PipelineRun is the part of a Tekton PipelineRun officer_ci_logs reads.

func ParsePipelineRun added in v0.125.0

func ParsePipelineRun(obj map[string]any) PipelineRun

ParsePipelineRun reads a tekton.dev/v1 PipelineRun object.

type PushGate

type PushGate struct {
	// Repo is the officer's repository (owner/name): the one a request naming
	// no repository is served for.
	Repo string
	// Ship is the officer's policy (Base, BranchPrefix; Repos for a draft
	// officer shipping to several repositories, each with its own base and
	// prefix: officers.Ship.RepoList).
	Ship *officers.Ship
	// OfficerID is the officer's id: a draft officer's branch shape, body
	// contract and notices name it.
	OfficerID string
	// GitHost and APIHost are the hosts served (github.com, api.github.com).
	GitHost, APIHost string
	// Cred mints the credential for an admitted request to a SHIP repository
	// (the officer App's connectors.Virtual Credential: its token for
	// caller.Repo, anonymous elsewhere).
	Cred func(ctx context.Context, caller connectors.Caller, host, rest string) (string, bool, error)
	// ReadCred, when set, mints the READ-ONLY credential for a request to one
	// of the caller's read repositories (caller.ReadRepos): the deployment
	// App's, never the officer's. nil: such a request goes anonymously. Admit
	// forwards no write to a repository outside the ship repositories, so
	// ReadCred only ever serves reads.
	ReadCred func(ctx context.Context, caller connectors.Caller, host, rest string) (string, bool, error)
	// OnRejected drops a cached credential after a 401.
	OnRejected func(caller connectors.Caller)
	// GH reads a pull request (PATCH's own-PR check) and the App's slug, for
	// Repo. GHFor, when set, is the GitHub of each ship repository, keyed by
	// its lower-cased owner/name (a draft officer with several); Repo's entry,
	// when missing, is GH.
	GH    GitHub
	GHFor map[string]GitHub
	// Announce posts a draft officer's content refusal (a forbidden path, a
	// removed manifest kind, a secret shape) to HQ. A failure is logged by
	// Logf; the refusal stands either way.
	Announce func(ctx context.Context, n officers.Notice) error
	Logf     func(format string, args ...any)
	// Now is the clock the daily limit reads (time.Now when nil).
	Now func() time.Time
	// ItemClaimed answers whether HQ shows instance (the agent's name)
	// holding item of this officer under a live lease: a draft officer's new
	// pull request names its item in its branch, and the item must be one the
	// instance claimed. nil: every new pull request is refused (fail closed).
	ItemClaimed func(ctx context.Context, instance string, item int) error
	// CreateWait bounds how long a draft officer's new pull request waits for
	// another one of its creates to finish (DefaultCreateWait when 0).
	CreateWait time.Duration
	// contains filtered or unexported fields
}

PushGate is a shipping officer's connectors.Gate: the write filter every one of its instance's GitHub requests passes through in muster's connector proxy, and the source of the (write-capable) credential an admitted request carries.

🔴 IT IS AN ALLOWLIST. A read (GET, HEAD) is forwarded. A write is forwarded only when it is one of these, in the officer's own repository:

  • git push (POST …/git-receive-pack) whose EVERY ref update targets refs/heads/<prefix>… — so never the base branch, never a tag;
  • git fetch (POST …/git-upload-pack), which writes nothing;
  • POST /repos/{repo}/pulls with head <prefix>… and base = the base branch;
  • PATCH /repos/{repo}/pulls/{n} of the officer's OWN pull request (its App's bot authored it, its head is <prefix>…), title/body/state only — never `draft`, which REST PATCH does not take: draft -> ready is the officer_mark_ready tool (GraphQL, after the same own-PR gates);
  • POST /repos/{repo}/issues/{n}/comments on its OWN pull request.

Every other method, path and host shape is refused — the merge endpoint, the git/refs and git/tags endpoints, releases, the contents API (which commits to any branch), the merges API, GraphQL (which can do all of those), and every DELETE. Merges and tags are made by officer_merge_pr and officer_tag_release in muster-server, after their gates.

func (*PushGate) Admit

func (g *PushGate) Admit(r *http.Request, host, rest string) (*http.Request, error)

Admit implements connectors.Gate.

func (*PushGate) Connector

func (g *PushGate) Connector() string

Connector implements connectors.Gate.

func (*PushGate) Credential

func (g *PushGate) Credential(ctx context.Context, caller connectors.Caller, host, rest string) (string, bool, error)

Credential implements connectors.Gate.

🔴 THE OFFICER APP'S TOKEN IS MINTED FOR A SHIP REPOSITORY ONLY. A request that names a ship repository is served for that one (caller.Repo); a request naming none for g.Repo; a request naming one of the caller's read repositories by ReadCred (the deployment App, read-only); any other repository anonymously. The officer App never sees caller.ReadRepos.

func (*PushGate) Describe

func (g *PushGate) Describe() connectors.Connector

Describe implements connectors.Gate: the GitHub preset's shape.

func (*PushGate) Rejected

func (g *PushGate) Rejected(caller connectors.Caller)

Rejected implements connectors.Gate.

func (*PushGate) Sweep added in v0.156.0

func (g *PushGate) Sweep(ctx context.Context) error

Sweep is the draft sweep: every open pull request the officer's App opened in each ship repository (OfficerPRs, every page), re-read for its current head and, unless that head was already checked clean, checked through checkComparison and answered like a push. 🔴 An unreadable comparison (or forbidden-path list) is retried on the next sweep, and closes the pull request once it has failed maxSweepMisses sweeps in a row: a GitHub blip closes nothing, a comparison that stays unreadable is not left open.

type REST

type REST struct {
	Base  string // API base, no trailing slash
	Repo  string // owner/name
	Token func(ctx context.Context) (string, error)
	// Slug reads the App's slug (GET /app, as the App).
	Slug func(ctx context.Context) (string, error)
	HTTP *http.Client
}

REST is GitHub over GitHub's REST API for Repo, authenticated by Token (the officer App's installation token, minted per call by muster).

func (*REST) AppSlug

func (g *REST) AppSlug(ctx context.Context) (string, error)

AppSlug implements GitHub.

func (*REST) BranchSHA

func (g *REST) BranchSHA(ctx context.Context, branch string) (string, error)

BranchSHA implements GitHub.

func (*REST) Branches added in v0.156.0

func (g *REST) Branches(ctx context.Context, prefix string) ([]Branch, error)

Branches implements GitHub (git/matching-refs, every page).

func (*REST) CheckRuns

func (g *REST) CheckRuns(ctx context.Context, sha, name string) ([]CheckRun, error)

CheckRuns implements GitHub.

func (*REST) ClosePR added in v0.156.0

func (g *REST) ClosePR(ctx context.Context, n int) error

ClosePR implements GitHub.

func (*REST) Commit

func (g *REST) Commit(ctx context.Context, sha string) (string, []string, error)

Commit implements GitHub.

func (*REST) CommitTime added in v0.156.0

func (g *REST) CommitTime(ctx context.Context, sha string) (time.Time, error)

CommitTime implements GitHub.

func (*REST) Compare

func (g *REST) Compare(ctx context.Context, base, head string) (Compare, error)

Compare implements GitHub. 🔴 GitHub lists at most 300 files and 250 commits in one comparison; a comparison at either cap is refused rather than read as complete.

func (*REST) CreateCommit

func (g *REST) CreateCommit(ctx context.Context, message, tree string, parents []string) (string, error)

CreateCommit implements GitHub.

func (*REST) CreateRef

func (g *REST) CreateRef(ctx context.Context, ref, sha string) error

CreateRef implements GitHub. An existing ref is ErrRefExists.

func (*REST) CreateTag

func (g *REST) CreateTag(ctx context.Context, name, message, sha string, t Tagger) (string, error)

CreateTag implements GitHub: an annotated tag OBJECT (no ref yet).

func (*REST) DeleteBranch added in v0.156.0

func (g *REST) DeleteBranch(ctx context.Context, branch string) error

DeleteBranch implements GitHub.

func (*REST) FileAt

func (g *REST) FileAt(ctx context.Context, path, ref string) ([]byte, error)

FileAt implements GitHub (the raw bytes of path at ref).

func (*REST) MarkReady added in v0.123.0

func (g *REST) MarkReady(ctx context.Context, n int, nodeID string) error

MarkReady implements GitHub.

func (*REST) Merge

func (g *REST) Merge(ctx context.Context, n int, sha string) (string, error)

Merge implements GitHub: a squash merge that GitHub refuses (409) unless the head is still sha — the match-head-commit guard.

func (*REST) MergeInto

func (g *REST) MergeInto(ctx context.Context, base, head, message string) (string, error)

MergeInto implements GitHub (POST merges: head merged into branch base). A conflict is ErrMergeConflict.

func (*REST) OfficerPRs added in v0.156.0

func (g *REST) OfficerPRs(ctx context.Context, login, state string) ([]PR, error)

OfficerPRs implements GitHub.

func (*REST) OpenPR

func (g *REST) OpenPR(ctx context.Context, title, head, base, body string) (int, error)

OpenPR implements GitHub.

func (*REST) PR

func (g *REST) PR(ctx context.Context, n int) (PR, error)

PR implements GitHub.

func (*REST) PRComments

func (g *REST) PRComments(ctx context.Context, n int) ([]Comment, error)

PRComments implements GitHub: conversation comments, review bodies and review comments, every page.

func (*REST) PRFiles

func (g *REST) PRFiles(ctx context.Context, n int) ([]File, error)

PRFiles implements GitHub.

func (*REST) PRsForBranch added in v0.156.0

func (g *REST) PRsForBranch(ctx context.Context, branch, state string) ([]PR, error)

PRsForBranch implements GitHub.

func (*REST) PRsForCommit

func (g *REST) PRsForCommit(ctx context.Context, sha string) ([]PR, error)

PRsForCommit implements GitHub.

func (*REST) Statuses

func (g *REST) Statuses(ctx context.Context, sha string) (map[string]string, error)

Statuses implements GitHub (the combined status: the latest per context).

func (*REST) TagObject

func (g *REST) TagObject(ctx context.Context, sha string) (TagObject, error)

TagObject implements GitHub.

func (*REST) Tags

func (g *REST) Tags(ctx context.Context) ([]TagRef, error)

Tags implements GitHub: every refs/tags/v* ref.

type ReadyOutcome added in v0.123.0

type ReadyOutcome struct {
	PR     int      `json:"pr"`
	Ready  bool     `json:"ready"`
	Passed []string `json:"gates_passed"`
}

ReadyOutcome is what officer_mark_ready did.

type Refusal

type Refusal struct {
	Gate   string
	Reason string
}

Refusal is a gate that did not pass. Nothing was written.

func AsRefusal

func AsRefusal(err error) (*Refusal, bool)

AsRefusal reports whether err is a gate refusal.

func (*Refusal) Error

func (r *Refusal) Error() string

type Step added in v0.125.0

type Step struct {
	Name      string
	Container string
	// Terminated is false while the step has not ended.
	Terminated bool
	ExitCode   int
	Reason     string
}

Step is one step of a TaskRun: its container and how it ended.

type TagObject

type TagObject struct {
	SHA        string
	Tagger     string
	TaggedAt   time.Time
	TargetSHA  string
	TargetType string
	Message    string
}

TagObject is an annotated tag.

type TagOptions

type TagOptions struct {
	// Rollback is the rollout watch's own release of a revert: it skips the
	// in-flight, rate, quiet-hours and HQ-enabled gates (the release being
	// rolled back is the one in flight, and HQ may be what is down) and keeps
	// every other.
	Rollback bool
}

TagOptions are officer_tag_release's inputs.

type TagOutcome

type TagOutcome struct {
	Tag         string    `json:"tag"`
	SHA         string    `json:"sha"`
	Previous    string    `json:"previous"`
	PreviousSHA string    `json:"previous_sha"`
	TaggedAt    time.Time `json:"tagged_at"`
	Passed      []string  `json:"gates_passed"`
	Migrations  []string  `json:"migrations,omitempty"`
}

TagOutcome is what officer_tag_release did.

type TagRef

type TagRef struct {
	Name       string
	ObjectSHA  string
	ObjectType string // commit (lightweight) | tag (annotated)
}

TagRef is one refs/tags/* ref: its name and the object it points at.

type Tagger

type Tagger struct {
	Name, Email string
	When        time.Time
}

Tagger is who an annotated tag is made by.

type TaskFailure added in v0.125.0

type TaskFailure struct {
	Task        string   `json:"task"`
	TaskRun     string   `json:"task_run"`
	Reason      string   `json:"reason,omitempty"`
	Message     string   `json:"message,omitempty"`
	FailedSteps []string `json:"failed_steps,omitempty"`
	Excerpt     string   `json:"excerpt"`
	// Truncated: something was cut — a log read dropped the log's start, an
	// excerpt hit its byte share, or a line in it was clipped.
	Truncated bool `json:"truncated,omitempty"`
	// LogErrors are logs that could not be read (the pod pruned, …).
	LogErrors []string `json:"log_errors,omitempty"`
}

TaskFailure is one failed TaskRun.

type TaskRun added in v0.125.0

type TaskRun struct {
	Name string
	// PipelineRun is the TaskRun's tekton.dev/pipelineRun label.
	PipelineRun  string
	PipelineTask string
	PodName      string
	Succeeded    string
	Reason       string
	Message      string
	Steps        []Step
}

TaskRun is the part of a Tekton TaskRun officer_ci_logs reads.

func ParseTaskRun added in v0.125.0

func ParseTaskRun(obj map[string]any) TaskRun

ParseTaskRun reads a tekton.dev/v1 TaskRun object.

type Version

type Version struct{ Major, Minor, Patch int }

Version is a vMAJOR.MINOR.PATCH tag.

func ParseVersion

func ParseVersion(tag string) (Version, bool)

ParseVersion reads a release tag; ok is false for anything else.

func (Version) Less

func (v Version) Less(w Version) bool

Less orders versions.

func (Version) NextMinor

func (v Version) NextMinor() Version

NextMinor is the release after v: minor bumped, patch 0.

func (Version) String

func (v Version) String() string

type WatchStatus

type WatchStatus struct {
	Tag         string    `json:"tag"`
	SHA         string    `json:"sha"`
	Previous    string    `json:"previous"`
	ItemID      string    `json:"item_id,omitempty"`
	TaggedAt    time.Time `json:"tagged_at"`
	Phase       string    `json:"phase"`
	Verdict     string    `json:"verdict"`
	LiveAt      time.Time `json:"live_at,omitempty"`
	RevertPR    int       `json:"revert_pr,omitempty"`
	RollbackTag string    `json:"rollback_tag,omitempty"`
	Escalated   bool      `json:"escalated"`
	// Rollback is true for the watch of a ROLLBACK release: it is never itself
	// rolled back.
	Rollback bool     `json:"rollback"`
	Events   []string `json:"events"`
	Done     bool     `json:"done"`
}

WatchStatus is one release's watch, as officer_rollout_status reports it.

type Watcher

type Watcher struct {
	OfficerID string
	Repo      string
	Ship      *officers.Ship
	GH        GitHub
	Gates     *Gates
	HTTP      *http.Client
	Now       func() time.Time
	// Sleep waits d or until ctx ends (tests replace it).
	Sleep func(ctx context.Context, d time.Duration) error
	Logf  func(format string, args ...any)
	// contains filtered or unexported fields
}

Watcher watches one officer's releases, one at a time.

func (*Watcher) InFlight

func (w *Watcher) InFlight() (string, bool)

InFlight reports the tag of a release still being watched.

func (*Watcher) LiveVersion

func (w *Watcher) LiveVersion(ctx context.Context) (string, error)

LiveVersion is the version the service reports now (Gates.LiveVersion).

func (*Watcher) Resume

func (w *Watcher) Resume(ctx context.Context)

Resume restarts the watch of the newest release after a muster restart, when that release is the officer's own and still inside its watch window. A restart therefore costs at most the probes it missed, not the watch.

func (*Watcher) Start

func (w *Watcher) Start(ctx context.Context, rel TagOutcome, itemID string) error

Start begins watching a release in the background (ctx ends it). A watch already in flight is refused: officer_tag_release's in-flight gate makes that unreachable except by a rollback, which watches inline.

func (*Watcher) Status

func (w *Watcher) Status() (cur *WatchStatus, history []WatchStatus)

Status is the current (or last) watch and the earlier ones of this process.

func (*Watcher) Wait

func (w *Watcher) Wait()

Wait blocks until every watch goroutine has returned (shutdown, tests).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL