Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ the exact plan you reviewed.
| Host access | Agentless SSH, key authentication, and mandatory `known_hosts` verification. An optional one-hop jump host reaches private targets, with both hops verified and the agent never forwarded. |
| Runtime ownership | Generated Compose stays inspectable with `ob preview` and can be taken over permanently with `ob eject`. |
| Automation | Human output, JSON envelopes, and NDJSON event streams come from the same lifecycle service. |
| GitHub | Deploys, rollbacks, resumes and aborts are reported to GitHub deployments at the commit each image was built from, whether `ob` runs on a laptop, an agent or a GitHub Actions runner. |

Workload reconciliation is automatic; it needs no selection flag. Onebox
fingerprints the effective runtime contract, including the rendered service,
Expand Down Expand Up @@ -189,8 +190,10 @@ for agents.
- **Operate:** [databases](https://onebox.run/docs/guides/databases),
[backups](https://onebox.run/docs/guides/backups),
[migrations](https://onebox.run/docs/guides/migrations),
[secrets](https://onebox.run/docs/guides/secrets), and
[rollback](https://onebox.run/docs/guides/rollback)
[secrets](https://onebox.run/docs/guides/secrets),
[rollback](https://onebox.run/docs/guides/rollback),
[GitHub deployments](https://onebox.run/docs/guides/github-deployments), and
[deploying from GitHub Actions](https://onebox.run/docs/guides/deploy-from-github-actions)
- **Reference:** [project file](https://onebox.run/docs/reference/project-file),
[CLI](https://onebox.run/docs/reference/cli),
[errors](https://onebox.run/docs/reference/errors), and
Expand Down
35 changes: 35 additions & 0 deletions api/application/v1alpha2/application.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,41 @@
"description": "Typed dependencies operated outside Onebox. Their connection projection is trusted, but their lifecycle and backup remain external.",
"type": "object"
},
"github": {
"additionalProperties": false,
"description": "Report deploys and rollbacks to a GitHub repository's deployments, so they show in its Environments tab and reach tools that read deployment statuses.",
"properties": {
"apiUrl": {
"default": "https://api.github.com",
"description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. Because the project file names the host, ob sends a token there only when the operator's environment confirms the same URL in ONEBOX_GITHUB_API_URL, and never sends it a github.com token: the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.",
"examples": [
"https://github.example.com/api/v3"
],
"pattern": "^https?://",
"type": "string"
},
"repository": {
"description": "GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application. Expects owner/name, such as labstack/shop.",
"examples": [
"labstack/shop"
],
"pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$",
"type": "string"
},
"tokenEnv": {
"description": "Local environment-variable name containing a GitHub token with Deployments write access; it must contain GH or GITHUB and end in TOKEN, so a project file cannot name some other secret. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects an upper-case variable name containing GH or GITHUB and ending in TOKEN, such as SHOP_GH_TOKEN.",
"examples": [
"GH_TOKEN"
],
"pattern": "^[A-Z0-9_]*(GH|GITHUB)[A-Z0-9_]*TOKEN$",
"type": "string"
}
},
"required": [
"repository"
],
"type": "object"
},
"hooks": {
"additionalProperties": {
"anyOf": [
Expand Down
3 changes: 3 additions & 0 deletions cmd/ob-docgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,9 @@ var blocks = []block{
{Key: "notifications", Title: "notifications", Order: 100, Status: statusShipped,
Summary: "Named webhooks that receive selected operation and scheduled-job outcomes.",
ReadWhen: []string{"Sending deploy outcomes to Slack, Discord or an incident tool"}},
{Key: "github", Title: "github", Order: 110, Status: statusShipped,
Summary: "The GitHub repository whose deployments record each deploy and rollback, and the local token used to report them.",
ReadWhen: []string{"Showing deploys in a repository's Environments tab, on pull requests, or to tools that read deployment statuses"}},
{Key: "backupTargets", Slug: "backup-targets", Title: "backupTargets", Order: 200, Status: statusShipped,
Summary: "User-owned off-host S3-compatible repositories a protected service writes its backups to. Executable for the postgres driver; every other driver refuses a policy it cannot honour.",
ReadWhen: []string{"Declaring where a database's backups go", "Understanding why Onebox refuses a backup target that shares the protected host"}},
Expand Down
8 changes: 3 additions & 5 deletions cmd/ob/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,11 +593,10 @@ func runMutation(cmd *cobra.Command, g *globalFlags, request onebox.ExecuteReque
structured.event(event)
}
}
result, err := operationsService(cmd, g).Execute(cmd.Context(), request)
result, err := executeAndReport(cmd.Context(), operationsService(cmd, g), cfg, g, request, verb)
if err == nil && result.NoOp && request.Kind == onebox.KindDeploy && structured == nil {
renderDeployNoOp(newUI(cmd, g), request.Plan.Artifact.HostState.CurrentRelease)
}
notifyOperationOutcome(cmd.Context(), cfg, g, verb, result, err)
if structured != nil {
if outputErr := structured.finish(&result, err); outputErr != nil {
if err == nil {
Expand Down Expand Up @@ -781,15 +780,14 @@ func runDeploy(cmd *cobra.Command, g *globalFlags, planFile, approvalFile, backu
approval = &grant
}
}
result, err := pl.svc.Execute(cmd.Context(), onebox.ExecuteRequest{
result, err := executeAndReport(cmd.Context(), pl.svc, pl.cfg, g, onebox.ExecuteRequest{
Kind: onebox.KindDeploy, Plan: &pl.plan, Approval: approval, BreakLock: breakLock,
NoRollback: g.NoRollback, Redeploy: redeploy,
})
}, "deploy")
if err == nil && result.NoOp {
renderDeployNoOp(pl.ui, pl.plan.Artifact.HostState.CurrentRelease)
return nil
}
notifyOperationOutcome(cmd.Context(), pl.cfg, g, "deploy", result, err)
return err
}

Expand Down
190 changes: 190 additions & 0 deletions cmd/ob/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package main

import (
"context"
"errors"
"fmt"
"os"
"sync"

"github.com/labstack/onebox/internal/app"
"github.com/labstack/onebox/internal/engine"
"github.com/labstack/onebox/internal/ghdeploy"
"github.com/labstack/onebox/internal/journal"
"github.com/labstack/onebox/internal/onebox"
)

// githubAPIBase is the API the reports go to. A variable so tests can point it
// at a fake.
var githubAPIBase = ghdeploy.DefaultBaseURL

// githubReport is the GitHub side of one deploy, rollback, resume or abort. It is fail-open
// like notifications: every problem is a stderr warning and never the verb's
// result. A nil report does nothing.
type githubReport struct {
reporter *ghdeploy.Reporter
kind onebox.OperationKind
meta ghdeploy.Meta
commits map[string]string

once sync.Once
pending *ghdeploy.Pending
}

func githubWarn(message string) {
fmt.Fprintf(os.Stderr, "warn: github: %s\n", message)
}

// newGitHubReport prepares a report for a deploy, rollback, resume or abort when the project
// names a GitHub repository. Other verbs, and projects without a github block,
// get nil. The token is found only when there is something to report, and off
// the operation's own path.
func newGitHubReport(cfg *app.Resolved, g *globalFlags, request onebox.ExecuteRequest) *githubReport {
if cfg == nil || cfg.GitHub == nil {
return nil
}
switch request.Kind {
case onebox.KindDeploy, onebox.KindRollback, onebox.KindResume, onebox.KindAbort:
default:
return nil
}
tokenEnv := cfg.GitHub.TokenEnv
baseURL := githubAPIBase
if cfg.GitHub.APIURL != "" {
baseURL = cfg.GitHub.APIURL
}
report := &githubReport{
kind: request.Kind,
meta: ghdeploy.Meta{
Operator: journal.DefaultOperator(),
Runner: onebox.CurrentRunnerProvenance().Version,
},
reporter: &ghdeploy.Reporter{
Client: &ghdeploy.Client{
BaseURL: baseURL, Repository: cfg.GitHub.Repository,
TokenSource: func(ctx context.Context) (string, error) {
return ghdeploy.ResolveToken(ctx, tokenEnv, cfg.GitHub.APIURL)
},
},
Environment: g.Env,
App: cfg.Name,
Warn: githubWarn,
},
}
if request.Kind == onebox.KindDeploy && request.Plan != nil {
report.commits = request.Plan.Artifact.SourceCommits
report.meta.ReleaseID = request.Plan.Operation.ReleaseID
report.meta.Description = "ob deploy " + report.meta.ReleaseID
}
return report
}

// events wraps an operation's event sink. A deploy is reported from the
// engine's release event, which follows the journal's deploy start: by then
// the lock, preconditions and preflight have passed and a no-op has returned,
// so a deploy refused before it touched the host is never announced. The sink
// is synchronous, so the report is only started here.
func (r *githubReport) events(ctx context.Context, next onebox.EventSink) onebox.EventSink {
if r == nil || r.kind != onebox.KindDeploy {
return next
}
return func(event onebox.OperationEvent) {
if next != nil {
next(event)
}
if event.Kind == onebox.KindDeploy && event.Phase == "release" {
r.once.Do(func() {
if len(r.commits) == 0 {
githubWarn("not reported: the plan names no commit; push and plan from a clean checkout of the repository, or label the images with org.opencontainers.image.source and org.opencontainers.image.revision")
return
}
r.pending = r.reporter.Start(context.WithoutCancel(ctx), r.commits, r.meta)
})
}
}
}

// finish posts the outcome. A deploy's deployments get their final status; a
// rollback is recorded now, because the commits it restores are known only
// once it has resolved its target under the lock.
func (r *githubReport) finish(ctx context.Context, result onebox.OperationResult, err error) {
if r == nil {
return
}
ctx = context.WithoutCancel(ctx)
switch r.kind {
case onebox.KindDeploy:
if r.pending == nil {
return
}
state, description := deployOutcome(r.meta.ReleaseID, err)
r.pending.Finish(ctx, state, description)
case onebox.KindRollback:
if err != nil || result.ReleaseID == "" {
return
}
if len(result.SourceCommits) == 0 {
githubWarn("not reported: release " + result.ReleaseID + " recorded no commits; it was deployed before GitHub reporting was configured")
return
}
meta := r.meta
meta.ReleaseID = result.ReleaseID
meta.Description = "ob rollback to " + result.ReleaseID
r.reporter.Record(ctx, result.SourceCommits, meta, ghdeploy.StateSuccess)
case onebox.KindResume:
// The interrupted deploy's deployments get the outcome it finally
// had; one that is now serving is put on record even when the
// interrupted run never reached GitHub. A release that recorded no
// commits was not reported to begin with, and stays quiet.
if len(result.SourceCommits) == 0 || result.EvidenceID == "" {
return
}
meta := r.meta
meta.ReleaseID = result.EvidenceID
state, description := deployOutcome(result.EvidenceID, err)
meta.Description = "ob resume: " + description
r.reporter.Conclude(ctx, result.SourceCommits, meta, state, err == nil)
case onebox.KindAbort:
if err != nil || len(result.SourceCommits) == 0 || result.EvidenceID == "" {
return
}
meta := r.meta
meta.ReleaseID = result.EvidenceID
meta.Description = "ob abort reverted " + result.EvidenceID
r.reporter.Conclude(ctx, result.SourceCommits, meta, ghdeploy.StateFailure, false)
}
}

// deployOutcome maps a deploy's result to a deployment status. A failure
// after activation leaves the release serving, which GitHub's failure would
// deny, and an interrupted deploy did not fail on its own terms: both are
// errors.
func deployOutcome(releaseID string, err error) (state, description string) {
var postActivation *engine.PostActivationFailedError
switch {
case err == nil:
return ghdeploy.StateSuccess, "ob deploy " + releaseID + " succeeded"
case errors.As(err, &postActivation):
return ghdeploy.StateError, releaseID + " is serving, but the work after activation did not finish"
case errors.Is(err, context.Canceled):
return ghdeploy.StateError, "ob deploy " + releaseID + " was interrupted; inspect with ob status"
default:
return ghdeploy.StateFailure, "ob deploy " + releaseID + " failed; inspect trusted local diagnostics"
}
}

// executeAndReport runs one canonical operation and reports its outcome to
// notifications and GitHub. Both deploy paths and every other mutation share
// it, so no verb reports differently from another.
func executeAndReport(ctx context.Context, svc *onebox.Service, cfg *app.Resolved, g *globalFlags, request onebox.ExecuteRequest, verb string) (onebox.OperationResult, error) {
report := newGitHubReport(cfg, g, request)
request.Events = report.events(ctx, request.Events)
result, err := svc.Execute(ctx, request)
// Each reporter is bounded on its own; run together, a dead receiver of
// either costs one bound, not the two added.
var wg sync.WaitGroup
wg.Go(func() { notifyOperationOutcome(ctx, cfg, g, verb, result, err) })
wg.Go(func() { report.finish(ctx, result, err) })
wg.Wait()
return result, err
}
Loading
Loading